我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用twisted.internet.task.LoopingCall()。
def run(self): ''' Called by twisted ''' # load initial config self.refresh_config() if self.config is None: logging.critical("cannot start due to error in config file") return # refresh and check status every event_period seconds self.refresh_task = task.LoopingCall(self.refresh_loop) refresh_deferred = self.refresh_task.start(self.config['event_period'], now=False) refresh_deferred.addErrback(errorCallback) # setup server for receiving blinded counts from the DC nodes and key shares from the SK nodes listen_port = self.config['listen_port'] key_path = self.config['key'] cert_path = self.config['cert'] ssl_context = ssl.DefaultOpenSSLContextFactory(key_path, cert_path) logging.info("Tally Server listening on port {}".format(listen_port)) reactor.listenSSL(listen_port, self, ssl_context) reactor.run()
def handle_checkin_event(self, event_type, event_payload): if event_type == "CHECKIN": parts = event_payload.split() if len(parts) == 1: period = int(parts[0]) # we have to store the checkin task in the factory, # because the protocol is re-created on every connection checkin_task = self.factory.get_checkin_task() if checkin_task is not None and checkin_task.running: checkin_task.stop() self.factory.set_checkin_task(None) checkin_task = task.LoopingCall(self.factory.do_checkin) self.factory.set_checkin_task(checkin_task) # we ignore any errors from do_checkin, see bug #47 checkin_deferred = checkin_task.start(period, now=False) checkin_deferred.addErrback(errorCallback) self.sendLine("CHECKIN SUCCESS") self.protocol_succeeded() return True return False
def __init__(self, settings, crawl_keypair_filename=None, dispersy_port=-1): if Tunnel.__single: raise RuntimeError("Tunnel is singleton") Tunnel.__single = self self.settings = settings self.should_run = True self.crawl_keypair_filename = crawl_keypair_filename self.dispersy_port = dispersy_port self.crawl_data = defaultdict(lambda: []) self.crawl_message = {} self.current_stats = [0, 0, 0] self.history_stats = deque(maxlen=180) self.start_tribler() self.dispersy = self.session.lm.dispersy self.multichain_community = None self.community = None self.clean_messages_lc = LoopingCall(self.clean_messages) self.clean_messages_lc.start(1800) self.build_history_lc = LoopingCall(self.build_history) self.build_history_lc.start(60, now=True)
def drive_to_resolution(self): """ Note: this overrides the method defined in ResolutionStrategyMixin """ if self.master_uid == self.network_uid: self.stop_driving() if self.paxos.proposal_id.number == 1: self.send_accept(self.paxos.proposal_id, self.paxos.proposed_value) else: self.paxos.prepare() self.retransmit_task = task.LoopingCall( lambda : self.send_prepare(self.paxos.proposal_id) ) self.retransmit_task.start( self.retransmit_interval/1000.0, now=False ) else: super(DedicatedMasterStrategyMixin,self).drive_to_resolution()
def main(): # Setup the blockchain blockchain = LevelDBBlockchain(settings.LEVELDB_PATH) Blockchain.RegisterBlockchain(blockchain) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) NodeLeader.Instance().Start() # Start a thread with custom code d = threading.Thread(target=custom_background_code) d.setDaemon(True) # daemonizing the thread will kill it when the main thread is quit d.start() # Run all the things (blocking call) reactor.run() logger.info("Shutting down.")
def main(): # Setup the blockchain blockchain = LevelDBBlockchain(settings.LEVELDB_PATH) Blockchain.RegisterBlockchain(blockchain) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) NodeLeader.Instance().Start() # Disable smart contract events for external smart contracts settings.set_log_smart_contract_events(False) # Start a thread with custom code d = threading.Thread(target=custom_background_code) d.setDaemon(True) # daemonizing the thread will kill it when the main thread is quit d.start() # Hook up Klein API to Twisted reactor endpoint_description = "tcp:port=%s:interface=localhost" % API_PORT endpoint = endpoints.serverFromString(reactor, endpoint_description) endpoint.listen(Site(app.resource())) # Run all the things (blocking call) logger.info("Everything setup and running. Waiting for events...") reactor.run() logger.info("Shutting down.")
def main(): # Setup the blockchain blockchain = LevelDBBlockchain(settings.LEVELDB_PATH) Blockchain.RegisterBlockchain(blockchain) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) NodeLeader.Instance().Start() # Disable smart contract events for external smart contracts settings.set_log_smart_contract_events(False) # Start a thread with custom code d = threading.Thread(target=custom_background_code) d.setDaemon(True) # daemonizing the thread will kill it when the main thread is quit d.start() # Run all the things (blocking call) logger.info("Everything setup and running. Waiting for events...") reactor.run() logger.info("Shutting down.")
def startup(urls, loop_times, stats_man, ep_man): stats_man.initialize_client_list(ep_man.endpoints) # start loop to periodically collect and report stats stats_loop = task.LoopingCall(stats_man.stats_loop) stats_loop_deferred = stats_loop.start(loop_times["stats"]) stats_loop_deferred.addCallback(stats_man.stats_loop_done) stats_loop_deferred.addErrback(stats_man.stats_loop_failed) # start loop to periodically update the list of validator endpoints # and call WorkManager.update_client_list ep_loop = task.LoopingCall(ep_man.update_endpoint_discovery, stats_man.update_client_list) ep_loop_deferred = ep_loop.start(loop_times["endpoint"], now=False) ep_loop_deferred.addCallback(ep_man.update_endpoint_done) ep_loop_deferred.addErrback(ep_man.update_endpoint_failed)
def init_linuxcnc(self): self.stat = linuxcnc.stat() self.command = linuxcnc.command() self.error_channel = linuxcnc.error_channel() try: self.stat.poll() except linuxcnc.error as e: self.error('Unable to poll linuxcnc, is it running?') self.error('Error message: {}'.format(e)) return self.serial = self.stat.echo_serial_number self.cmd_serial = self.serial + 1 self.error_channel.poll() self.last_interp_state = self.stat.interp_state self.poll_task = task.LoopingCall(self.poll_linuxcnc) self.poll_task.start(0.1) self.state = 'READY'
def __init__(self, feedurl, pollinterval=3600): """ @type feedurl: string @param feedurl: The Atom feed URL of the GoogleCode repo (e.g. http://code.google.com/feeds/p/ostinato/hgchanges/basic) @type pollinterval: int @param pollinterval: The time (in seconds) between queries for changes (default is 1 hour) """ self.feedurl = feedurl self.branch = None self.pollinterval = pollinterval self.lastChange = None self.loop = LoopingCall(self.poll)
def send_tx4_sig(self): """Send partial signature on TX4 (out of TX0) to Carol for her to complete sign and broadcast. """ utxo_in = self.tx0.txid + ":" + str(self.tx0.pay_out_index) self.tx4 = CoinSwapTX45.from_params(self.coinswap_parameters.pubkeys["key_2_2_AC_0"], self.coinswap_parameters.pubkeys["key_2_2_AC_1"], utxo_in=utxo_in, destination_address=self.coinswap_parameters.output_addresses["tx4_address"], destination_amount=self.coinswap_parameters.tx4_amounts["carol"], carol_change_address=None, carol_change_amount=None) self.tx4.sign_at_index(self.keyset["key_2_2_AC_0"][0], 0) sig = self.tx4.signatures[0][0] self.send(sig, self.tx5.txid) self.tx4broadcast_counter = 0 self.loop_tx4 = task.LoopingCall(self.wait_for_tx4_confirmation) self.loop_tx4.start(3.0) return (True, "TX4 signature sent.")
def runcase(alice_class, carol_class, fail_alice_state=None, fail_carol_state=None): options_server = Options() wallets = make_wallets(num_alices + 1, wallet_structures=wallet_structures, mean_amt=funding_amount) args_server = ["dummy"] test_data_server = (wallets[num_alices]['seed'], args_server, options_server, False, None, carol_class, None, fail_carol_state) carol_bbmb = main_cs(test_data_server) options_alice = Options() options_alice.serve = False alices = [] for i in range(num_alices): args_alice = ["dummy", amounts[i]] if dest_addr: args_alice.append(dest_addr) test_data_alice = (wallets[i]['seed'], args_alice, options_alice, False, alice_class, None, fail_alice_state, None) alices.append(main_cs(test_data_alice)) l = task.LoopingCall(miner) reactor.callWhenRunning(start_mining, l) reactor.run() return (alices, carol_bbmb, wallets[num_alices]['wallet'])
def start(self, netserver): """Start the application interface Args: netserver (NetServer): The LoRa network server Returns True on success, False otherwise """ self.netserver = netserver self.polling = False if not hasattr(self, 'task'): self.task = task.LoopingCall(self._pollInboundMessages) # Setup the looping task to query for messages self.task.start(self.poll_interval * 60) # Set the running flag self.started = True returnValue(True) yield
def syncWalletUpdate(self, fast, restart_cb=None): if restart_cb: fast=False #Special syncing condition for Electrum iselectrum = jm_single().config.get("BLOCKCHAIN", "blockchain_source") == "electrum-server" if iselectrum: jm_single().bc_interface.synctype = "with-script" jm_single().bc_interface.sync_wallet(self.wallet, fast=fast, restart_cb=restart_cb) if iselectrum: #sync_wallet only initialises, we must manually call its entry #point here (because we can't use connectionMade as a trigger) jm_single().bc_interface.sync_addresses(self.wallet) self.wait_for_sync_loop = task.LoopingCall(self.updateWalletInfo) self.wait_for_sync_loop.start(0.2) else: self.updateWalletInfo()
def confirm_callback(self, txd, txid, confirmations): #find the offer for this tx offerinfo = None for k,v in self.finalized_offers.iteritems(): #Tx considered defined by its output set if v["txd"]["outs"] == txd["outs"]: offerinfo = v break if not offerinfo: jlog.info("Failed to find notified unconfirmed transaction: " + txid) return jm_single().bc_interface.wallet_synced = False jm_single().bc_interface.sync_unspent(self.client.wallet) jlog.info('tx in a block: ' + txid) self.wait_for_sync_loop = task.LoopingCall(self.modify_orders, offerinfo, confirmations, txid) self.wait_for_sync_loop.start(2.0)
def __init__(self, jsonRpc, network): super(BitcoinCoreInterface, self).__init__() self.jsonRpc = jsonRpc self.fast_sync_called = False blockchainInfo = self.jsonRpc.call("getblockchaininfo", []) actualNet = blockchainInfo['chain'] netmap = {'main': 'mainnet', 'test': 'testnet', 'regtest': 'regtest'} if netmap[actualNet] != network: raise Exception('wrong network configured') self.txnotify_fun = [] self.wallet_synced = False #task.LoopingCall objects that track transactions, keyed by txids. #Format: {"txid": (loop, unconfirmed true/false, confirmed true/false, #spent true/false), ..} self.tx_watcher_loops = {}
def __init__(self, host=defaultHost, port=4400, redisPort=6379, neo4jPort=7474, initialKey=None): #self.protocol = Peer(self) self.host = host self.port = port self.users = {} # maps user names to Chat instances self.redisPort = redisPort self.neo4jPort = neo4jPort if initialKey: # need test case self.commandKeys.append(initialKey) # self.redis.addToKeys(initialKey) """Add loops to factory? why not add loops to main reactor??""" defly = task.deferLater(reactor, 10, self.ping) defly.addErrback(whoops) #reactor.callLater(2, redis_test) #task.deferLater(reactor, 60, hiya).addCallback(lambda _: reactor.stop()) loop = task.LoopingCall(peerBeat) loopDeferred = loop.start(15.0) loopDeferred.addCallback(peerSuccess) loopDeferred.addErrback(peerFailure) # pylint: disable=no-self-use
def __init__(self, task_id, cid, vservice): """Constructor""" self._task_id = task_id self._cid = cid self._vservice = vservice assert isinstance(self._vservice, VService) self._conn = vservice.get_conn_by_cid(cid) # pri attrs self._result = None self._ack_flag = False self._STATE = client.TASK_STATE_PENDING self._retry_times = 0 self._waitingack = False # # looping call to ack # self._loopingcall_ack = LoopingCall(self._checking_ack) #----------------------------------------------------------------------
def register_task(self, name, task, delay=None, value=None, interval=None): """ Register a task so it can be canceled at shutdown time or by name. """ assert not self.is_pending_task_active(name), name assert isinstance(task, (Deferred, DelayedCall, LoopingCall)), (task, type(task) == type(Deferred)) if delay is not None: if isinstance(task, Deferred): if value is None: raise ValueError("Expecting value to fire the Deferred with") dc = self._reactor.callLater(delay, task.callback, value) elif isinstance(task, LoopingCall): if interval is None: raise ValueError("Expecting interval for delayed LoopingCall") dc = self._reactor.callLater(delay, task.start, interval) else: raise ValueError("Expecting Deferred or LoopingCall if task is delayed") task = (dc, task) self._maybe_clean_task_list() with self._task_lock: self._pending_tasks[name] = task return task
def _get_isactive_stopper(self, name): """ Return a boolean determining if a task is active and its cancel/stop method if the task is registered. """ task = self._pending_tasks.get(name, None) def do_get(task): if isinstance(task, Deferred): # Have in mind that any deferred in the pending tasks list should have been constructed with a # canceller function. return not task.called, getattr(task, 'cancel', None) elif isinstance(task, DelayedCall): return task.active(), task.cancel elif isinstance(task, LoopingCall): return task.running, task.stop elif isinstance(task, tuple): if task[0].active(): return task[0].active(), task[0].cancel else: return do_get(task[1]) else: return False, None return do_get(task)
def test_delayed_looping_call_register_wait_and_cancel(self): self.assertFalse(self.tm.is_pending_task_active("test")) lc = LoopingCall(self.count) lc.clock = self.tm._reactor self.tm.register_task("test", lc, delay=1, interval=1) self.assertTrue(self.tm.is_pending_task_active("test")) # After one second, the counter has increased by one and the task is still active. self.tm._reactor.advance(1) self.assertEquals(1, self.counter) self.assertTrue(self.tm.is_pending_task_active("test")) # After one more second, the counter should be 2 self.tm._reactor.advance(1) self.assertEquals(2, self.counter) # After canceling the task the counter should stop increasing self.tm.cancel_pending_task("test") self.assertFalse(self.tm.is_pending_task_active("test")) self.tm._reactor.advance(10) self.assertEquals(2, self.counter)
def stop(self): """ Cleanup our LoopingCall and any outstanding deferreds... """ self.stopping = True # Cancel any outstanding request to our client if self._batch_send_d: self._batch_send_d.cancel() # Do we have to worry about our looping call? if self.batch_every_t is not None: # Stop our looping call, and wait for the deferred to be called if self.sendLooper is not None: self.sendLooper.stop() # Make sure requests that wasn't cancelled above are now self._cancel_outstanding() # # Private Methods # #
def __init__(self, factory): self.tc = TrustChain() self.factory = factory self.collect_rubbish_lc = task.LoopingCall(self._collect_rubbish) self.collect_rubbish_lc.start(5, False).addErrback(my_err_back) self.log_tx_count_lc = task.LoopingCall(self._log_info) self.log_tx_count_lc.start(5, False).addErrback(my_err_back) self.bootstrap_lc = None self.random_node_for_tx = False # attributes below are states for building new CP blocks self.round_states = defaultdict(RoundState) self._initial_promoters = [] random.seed()
def initServer(self): self.password = os.environ['LABRADPASSWORD'] self.name = socket.gethostname() + ' Single Channel Lock Server' self.set_frequency = 658.116220 self.timer = 0.1 self.low_rail = 0 self.high_rail =30.0 self.p_gain = 1e-3 # Gain of piezo controller is 15V/V self.i_gain = 1e-5 # Not using now since lock is pretty good self.integral = 0 # to use for I self.prev_output = 0.0 self.dac_chan = 7 self.lasers = multiplexer_config.info self.laser_chan = '455nm' self.lc = LoopingCall(self.loop) self.output = 0.0 self.connect()
def connect(self): """ Connect to MQTT broker. """ # TODO: This is currently done synchronous which could have issues in timeout situations # because it would block other subsystems. # => Check if we can do asynchronous connection establishment. self.client = mqtt.Client(client_id=self.name, clean_session=True, userdata={'foo': 'bar'}) if self.broker_username: self.client.username_pw_set(self.broker_username, self.broker_password) self.client.on_connect = lambda *args: reactor.callFromThread(self.on_connect, *args) self.client.on_message = lambda *args: reactor.callFromThread(self.on_message, *args) self.client.on_log = lambda *args: reactor.callFromThread(self.on_log, *args) # Connect with retry self.connect_loop = LoopingCall(self.connect_with_retry) self.connect_loop.start(self.retry_interval, now=True)
def _checkLoop(self): """ Start or stop a C{LoopingCall} based on whether there are readers and writers. """ if self._readers or self._writers: if self._loop is None: from twisted.internet.task import LoopingCall, _EPSILON self._loop = LoopingCall(self.iterate) self._loop.clock = self._reactor # LoopingCall seems unhappy with timeout of 0, so use very # small number: self._loop.start(_EPSILON, now=False) elif self._loop: self._loop.stop() self._loop = None
def loopUntil(predicate, interval=0): """ Poor excuse for an event notification helper. This polls a condition and calls back a Deferred when it is seen to be true. Do not use this function. """ from twisted.internet import task d = defer.Deferred() def check(): res = predicate() if res: d.callback(res) call = task.LoopingCall(check) def stop(result): call.stop() return result d.addCallback(stop) d2 = call.start(interval) d2.addErrback(d.errback) return d
def test_reset(self): """ Test that L{LoopingCall} can be reset. """ ran = [] def foo(): ran.append(None) c = task.Clock() lc = TestableLoopingCall(c, foo) lc.start(2, now=False) c.advance(1) lc.reset() c.advance(1) self.assertEqual(ran, []) c.advance(1) self.assertEqual(ran, [None])
def test_deferredDeprecation(self): """ L{LoopingCall.deferred} is deprecated. """ loop = task.LoopingCall(lambda: None) loop.deferred message = ( 'twisted.internet.task.LoopingCall.deferred was deprecated in ' 'Twisted 16.0.0; ' 'please use the deferred returned by start() instead' ) warnings = self.flushWarnings([self.test_deferredDeprecation]) self.assertEqual(1, len(warnings)) self.assertEqual(DeprecationWarning, warnings[0]['category']) self.assertEqual(message, warnings[0]['message'])
def __init__(self, *a): Output.__init__(self, *a) self.events = [] self.timer = task.LoopingCall(self.tick) self.inter = float(self.config.get('interval', 1.0)) # tick interval self.maxsize = int(self.config.get('maxsize', 250000)) self.user = self.config.get('user') self.password = self.config.get('password') self.client = None self.url = self.config.get('url', 'http://localhost:4242') maxrate = int(self.config.get('maxrate', 100)) if maxrate > 0: self.queueDepth = int(maxrate * self.inter) else: self.queueDepth = None
def __init__(self, *a): Output.__init__(self, *a) self.timer = task.LoopingCall(self.tick) self.inter = float(self.config.get('interval', 1.0)) # tick interval self.pressure = int(self.config.get('pressure', -1)) self.maxsize = int(self.config.get('maxsize', 250000)) self.expire = self.config.get('expire', False) self.allow_nan = self.config.get('allow_nan', True) self.factory = None self.connector = None maxrate = int(self.config.get('maxrate', 0)) if maxrate > 0: self.queueDepth = int(maxrate * self.inter) else: self.queueDepth = None self.tls = self.config.get('tls', False) if self.tls: self.cert = self.config['cert'] self.key = self.config['key']
def __init__(self, *a): Output.__init__(self, *a) self.events = [] self.timer = task.LoopingCall(self.tick) self.inter = float(self.config.get('interval', 1.0)) # tick interval self.maxsize = int(self.config.get('maxsize', 250000)) self.user = self.config.get('user') self.password = self.config.get('password') self.url = self.config.get('url', 'http://localhost:9200') maxrate = int(self.config.get('maxrate', 100)) self.index = self.config.get('index', 'duct-%Y.%m.%d') self.client = None if maxrate > 0: self.queueDepth = int(maxrate * self.inter) else: self.queueDepth = None
def _playlist_updated(self, pl): if pl.has_programs(): # if we got a program playlist, save it and start a program self._program_playlist = pl (program_url, _) = pl.get_program_playlist(self.program, self.bitrate) l = HLS.make_url(self.url, program_url) return self._reload_playlist(M3U8(l)) elif pl.has_files(): # we got sequence playlist, start reloading it regularly, and get files self._file_playlist = pl if not self._files: self._files = pl.iter_files() if not pl.endlist(): if not self._pl_task: self._pl_task = task.LoopingCall(self._reload_playlist, pl) self._pl_task.start(10, False) if self._file_playlisted: self._file_playlisted.callback(pl) self._file_playlisted = None else: raise return pl
def stats_setup(self): self.stats_snapshot_previous = None self.interval_histogram = HdrHistogram(1, 10000000, 3) self.ttl_histogram = HdrHistogram(1, 10000000, 3) self.msglag_histogram = HdrHistogram(1, 10000000, 3) namespace = "stats_{0!s}_{1!s}_depth_{2!s}".format(platform.node(), self.SenderCompID, self.config['market_depth']) filename = os.path.join(self.stats_dir, namespace+datetime.strftime(datetime.utcnow(), "_%Y%m%d%H%M%S")+'.log') self._stats_logger = Logger( observer=passThroughFileLogObserver(io.open(filename, "a")), namespace='') self.stats_loop = task.LoopingCall(self.log_stats) self.stats_loop.start(self.stats_interval)
def do_checkin(self): ''' Called by protocol Refresh the config, and try to connect to the server This function is usually called using LoopingCall, so any exceptions will be turned into log messages. ''' # TODO: Refactor common client code - issue #121 self.refresh_config() self.check_aggregator() ts_ip = self.config['tally_server_info']['ip'] ts_port = self.config['tally_server_info']['port'] # turn on reconnecting mode and reset backoff self.resetDelay() logging.info("checking in with TallyServer at {}:{}".format(ts_ip, ts_port)) reactor.connectSSL(ts_ip, ts_port, self, ssl.ClientContextFactory()) # pylint: disable=E1101
def start(self): ''' start the aggregator, and connect to the control port ''' # This call can return a list of connectors, or a single connector self.connector_list = connect(self, self.tor_control_port) # Twisted doesn't want a list of connectors, it only wants one self.connector = choose_a_connection(self.connector_list) self.rotator = task.LoopingCall(self._do_rotate) rotator_deferred = self.rotator.start(self.rotate_period, now=False) rotator_deferred.addErrback(errorCallback) # if we've already built the protocol before starting if self.protocol is not None: self.protocol.startCollection(self.collection_counters)
def startService(self): service.Service.startService(self) callable, args, kwargs = self.call # we have to make a new LoopingCall each time we're started, because # an active LoopingCall remains active when serialized. If # LoopingCall were a _VolatileDataService, we wouldn't need to do # this. self._loop = task.LoopingCall(callable, *args, **kwargs) self._loop.start(self.step, now=True).addErrback(self._failed)
def _failed(self, why): # make a note that the LoopingCall is no longer looping, so we don't # try to shut it down a second time in stopService. I think this # should be in LoopingCall. -warner self._loop.running = False log.err(why)
def __init__(self, conn): self.conn = conn self.globalTimeout = None self.lc = task.LoopingCall(self.sendGlobal) self.lc.start(300)
def __init__(self, site, uid): """Initialize a session with a unique ID for that session. """ components.Componentized.__init__(self) self.site = site self.uid = uid self.expireCallbacks = [] self.checkExpiredLoop = task.LoopingCall(self.checkExpired) self.touch() self.sessionNamespaces = {}
def install(widget, ms=10, reactor=None): """Install a Tkinter.Tk() object into the reactor.""" installTkFunctions() global _task _task = task.LoopingCall(widget.update) _task.start(ms / 1000.0, False)
def testBadDelay(self): lc = task.LoopingCall(lambda: None) self.assertRaises(ValueError, lc.start, -1) # Make sure that LoopingCall.stop() prevents any subsequent calls.
def testFailure(self): def foo(x): raise TestException(x) lc = task.LoopingCall(foo, "bar") return self.assertFailure(lc.start(0.1), TestException)
def testFailAndStop(self): def foo(x): lc.stop() raise TestException(x) lc = task.LoopingCall(foo, "bar") return self.assertFailure(lc.start(0.1), TestException)
def testEveryIteration(self): ran = [] def foo(): ran.append(None) if len(ran) > 5: lc.stop() lc = task.LoopingCall(foo) d = lc.start(0) def stopped(ign): self.assertEquals(len(ran), 6) return d.addCallback(stopped)
def testStopAtOnceLater(self): # Ensure that even when LoopingCall.stop() is called from a # reactor callback, it still prevents any subsequent calls. d = defer.Deferred() def foo(): d.errback(failure.DefaultException( "This task also should never get called.")) self._lc = task.LoopingCall(foo) self._lc.start(1, now=False) reactor.callLater(0, self._callback_for_testStopAtOnceLater, d) return d
def startService(self): service.Service.startService(self) self.calls = [task.LoopingCall(d.transfer) for d in self.domains] i = 0 from twisted.internet import reactor for c in self.calls: # XXX Add errbacks, respect proper timeouts reactor.callLater(i, c.start, 60 * 60) i += 1
def __init__(self, sc, bridge_nick, nickserv_pw, slack_uid, channels, user_bots): self.sc = sc self.user_bots = user_bots self.nickserv_password = nickserv_pw self.slack_uid = slack_uid self.users = {bot.user_id: bot for bot in user_bots} self.channels = {channel['id']: channel for channel in channels} self.channel_name_uid_map = {channel['name']: channel['id'] for channel in channels} self.nickname = bridge_nick self.message_queue = queue.PriorityQueue() self.rtm_connect() log.msg('Connected successfully to Slack RTM') # Create a looping call to poll Slack for updates rtm_loop = LoopingCall(self.check_slack_rtm) # Slack's rate limit is 1 request per second, so set this to something # greater than or equal to that to avoid problems rtm_loop.start(1) # Create another looping call which acts on messages in the queue message_loop = LoopingCall(self.empty_queue) message_loop.start(0.5)
def __init__(self, port=None, interface=b'*', update_interval=1 / 60.0): if port is not None and interface is not None: address = enet.Address(interface, port) else: address = None self.host = enet.Host(address, self.max_connections, 1) self.host.compress_with_range_coder() self.update_loop = LoopingCall(self.update) self.update_loop.start(update_interval, False) self.connections = {} self.clients = {}
def update(self): try: while 1: if self.host is None: return try: event = self.host.service(0) except IOError: break if event is None: break event_type = event.type if event_type == enet.EVENT_TYPE_NONE: break peer = event.peer is_client = peer in self.clients if is_client: connection = self.clients[peer] if event_type == enet.EVENT_TYPE_CONNECT: connection.on_connect() connection.timeout_call.cancel() elif event_type == enet.EVENT_TYPE_DISCONNECT: connection.on_disconnect() del self.clients[peer] self.check_client() elif event.type == enet.EVENT_TYPE_RECEIVE: connection.loader_received(event.packet) else: if event_type == enet.EVENT_TYPE_CONNECT: self.on_connect(peer) elif event_type == enet.EVENT_TYPE_DISCONNECT: self.on_disconnect(peer) elif event.type == enet.EVENT_TYPE_RECEIVE: self.data_received(peer, event.packet) except: # make sure the LoopingCall doesn't catch this and stops import traceback traceback.print_exc()