twisted.internet.reactor.callLater

Here are the examples of the python api twisted.internet.reactor.callLater taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

180 Examples 7

Example 1

Project: ZenPacks.zenoss.OpenStackInfrastructure Source File: client.py
def retry():
    log.debug('retrying')
    d = client.run('sleep 5 && ls')

    def failed_or_success(result):
        if isinstance(result, failure.Failure):
            log.info("Failed %s" % (result, ))
        else:
            log.info("Success %s" % (result, ))

    d.addBoth(failed_or_success)

    d2 = client.run('sleep 5 && ls', timeout=6)
    d2.addBoth(failed_or_success)
    reactor.callLater(6, retry)

Example 2

Project: greplin-twisted-utils Source File: time.py
def timeoutDeferred(seconds, deferred):
  """Returns a new deferred that returns the results of the first deferred, or errs back if on timeout."""
  if deferred.called:
    return deferred

  from twisted.internet import reactor
  timeout = reactor.callLater(seconds, lambda: defer.timeout(deferred))

  result = defer.Deferred()
  result.addCallback(lambda result: timeout.cancel() or result)
  deferred.chainDeferred(result)
  return result

Example 3

Project: sx Source File: client.py
Function: subscribe_address
    def subscribe_address(self, address, notification_cb=None, cb=None):
        address_version, address_hash = \
            bitcoin.bc_address_to_hash_160(address)
        # prepare parameters
        data = struct.pack('B', address_version)          # address version
        data += address_hash[::-1]               # address

        # run command
        self.send_command('address.subscribe', data, cb)
        if notification_cb:
            self._subscriptions['address'][address_hash] = notification_cb
        reactor.callLater(120, self.renew_address, address)

Example 4

Project: khashmir Source File: krpc.py
    def sendRequest(self, method, args):
        # make message
        # send it
        msg = {TID : chr(self.mtid), TYP : REQ,  REQ : method, ARG : args}
        self.mtid = (self.mtid + 1) % 256
        str = bencode(msg)
        d = Deferred()
        self.tids[msg[TID]] = d
        def timeOut(tids = self.tids, id = msg[TID]):
            if tids.has_key(id):
                df = tids[id]
                del(tids[id])
                print ">>>>>> KRPC_ERROR_TIMEOUT"
                df.errback(KRPC_ERROR_TIMEOUT)
        reactor.callLater(KRPC_TIMEOUT, timeOut)
        self.transport.write(str, self.addr)
        return d

Example 5

Project: txrdq Source File: test_rdq.py
    def testWiden(self):
        dq = ResizableDispatchQueue(self.slow, 2)
        map(dq.put, range(8))
        reactor.callLater(0.1, dq.setWidth, 10)
        # This should finish in about 0.4 seconds, with nothing on the
        # queue. We stop after 0.25 seconds. All tasks will have been
        # dispatched (width is initially 2 but is increased to 10 after the
        # first pair of jobs are underway).
        return self._stopAndTest(0.25, dq, [])

Example 6

Project: smap Source File: alerts.py
Function: read
  def read(self):
    data = self.client.latest(self.restrict, streamlimit=-1)
    for d in data:
      uuid = d["uuid"]
      latest = d["Readings"][0][0] / 1000
      now = time.time()
      gap = now - latest
      if gap > self.limit:
        self.alert(uuid)
        self.process.stop()
        reactor.callLater(self.alert_interval, self.start)
        break 

Example 7

Project: python-consul Source File: test_twisted.py
    @pytest.inlineCallbacks
    def test_kv_subscribe(self, consul_port):
        c = consul.twisted.Consul(port=consul_port)

        @defer.inlineCallbacks
        def put():
            response = yield c.kv.put('foo', 'bar')
            assert response is True

        reactor.callLater(1.0 / 100, put)
        index, data = yield c.kv.get('foo')
        assert data is None
        index, data = yield c.kv.get('foo', index=index)
        assert data['Value'] == six.b('bar')

Example 8

Project: scrapy Source File: http11.py
Function: close
    def close(self):
        d = self._pool.closeCachedConnections()
        # closeCachedConnections will hang on network or server issues, so
        # we'll manually timeout the deferred.
        #
        # Twisted issue addressing this problem can be found here:
        # https://twistedmatrix.com/trac/ticket/7738.
        #
        # closeCachedConnections doesn't handle external errbacks, so we'll
        # issue a callback after `_disconnect_timeout` seconds.
        delayed_call = reactor.callLater(self._disconnect_timeout, d.callback, [])

        def cancel_delayed_call(result):
            if delayed_call.active():
                delayed_call.cancel()
            return result

        d.addBoth(cancel_delayed_call)
        return d

Example 9

Project: mdk Source File: test_webclients.py
Function: render
    def render(self, request):
        delay = float(request.args.get(b"delay", [0])[0])
        self.received.append(
            request.requestHeaders.getRawHeaders(b"X-MDK-CONTEXT")[0])
        def done():
            request.write("")
            request.finish()
        reactor.callLater(delay, done)
        return NOT_DONE_YET

Example 10

Project: nodeset.core Source File: mnode_publish.py
def publish_main():
    n = SimpleNode(5688)
    application = service.Application('mnode-publish')

    reactor.callLater(1, n.subscribe, 'remote_event')
    reactor.callLater(2, _publish, n, 'event_1', 'payload_1')
    reactor.callLater(2, _publish, n, 'event_block', 'blocking')
    #reactor.callLater(3, n.publish, node.NodeEventBuilder().createEvent('event_2', 'payload_2'))
    reactor.callLater(4, _publish, n, 'event_3', 'payload_3')
    
    n.start()
    n.setServiceParent(application)
    
    run(application)

Example 11

Project: ants Source File: defer.py
def defer_succeed(result):
    """Same as twsited.internet.defer.succed, but delay calling callback until
    next reactor loop
    """
    d = defer.Deferred()
    reactor.callLater(0, d.callback, result)
    return d

Example 12

Project: ooni-backend Source File: handlers.py
def checkForStaleReports( _time=time):
    delayed_call = reactor.callLater(config.main.stale_time,
                                     checkForStaleReports)
    report_dir = FilePath(config.main.report_dir)
    for report_metadata_path in \
            report_dir.globChildren("*"+METADATA_EXT):
        last_updated = _time.time() - \
                       report_metadata_path.getModificationTime()
        if last_updated > config.main.stale_time:
            report_id = report_metadata_path.basename().replace(
                METADATA_EXT, '')
            closeReport(report_id)
    return delayed_call

Example 13

Project: b2bua Source File: Timeout.py
Function: init
    def __init__(self, timeout_callback, etime, *callback_arguments):
        etime = -etime.offsetFromNow()
        if etime < 0:
            etime = 0
        self._timeout_callback = timeout_callback
        self._task = reactor.callLater(etime, self._run_once, *callback_arguments)

Example 14

Project: simDHT Source File: kdht.py
    def refreshRoutingTable(self):
        """
        刷新路由表

        遇到不"新鲜"的bucket时, 随机选一个node, 发送find_node
        """
        for bucket in self.table:
            if bucket.isFresh(): continue

            node = bucket.random()
            if node is None: continue #如果该bucket无node, 继续下一个

            reactor.callLater(NEXT_FIND_NODE_INTERVAL, self.findNode, (node.ip, node.port))

Example 15

Project: freshen Source File: steps.py
@When("^I implement a step that returns a twisted Deferred object$")
def simulate_async_event():
    """Simulate an asynchronous event."""
    scc.state = 'executing'
    def async_event(result):
        """All other asynchronous events or function calls
        returned from later steps will wait until this
        callback fires."""
        scc.state = result
        return 'some event result'
    deferred = Deferred()
    reactor.callLater(1, deferred.callback, 'done') # pylint: disable=E1101
    deferred.addCallback(async_event)
    return deferred

Example 16

Project: campfirer Source File: client.py
Function: authenticated
    def authenticated(self, xs):
        log.msg('authed')
        presence = domish.Element((None, 'presence'))
        xs.send(presence)

        presence = domish.Element((None, 'presence'))
        presence['from'] = CONFIG['jid']
        presence['to'] = CONFIG['room']
        x = presence.addElement('x', 'http://jabber.org/protocol/muc')
        x.addElement('password', content=CONFIG['roompasswd'])
        xs.send(presence)
        reactor.callLater(10, self.say, "hello there %i" % time.time())

Example 17

Project: txTelegramBot Source File: twistedclient.py
    @defer.inlineCallbacks
    def _poll_updates(self, _=None):
        while self._poll:
            yield threads.deferToThread(self._poll_updates_thread)
            if self._poll_backoff:
                d = defer.Deferred()
                reactor.callLater(self._poll_backoff, d.callback, None)
                log.msg('Backing off update poll for %s' % self._poll_backoff)
                self._poll_backoff = 0
                yield d

Example 18

Project: multi-paxos-example Source File: master_strategy.py
    def start_master_lease_timer(self):
        self.lease_start = time.time()
        
        if self.lease_expiry is not None and self.lease_expiry.active():
            self.lease_expiry.cancel()
            
        self.lease_expiry = reactor.callLater(self.lease_window, self.lease_expired)

Example 19

Project: Limnoria Source File: Twisted.py
    def checkIrcForMsgs(self):
        if self.connected:
            msg = self.irc.takeMsg()
            while msg:
                self.transport.write(str(msg))
                msg = self.irc.takeMsg()
        self.mostRecentCall = reactor.callLater(0.1, self.checkIrcForMsgs)

Example 20

Project: python-obelisk Source File: query-blockchain.py
Function: poll_latest
def poll_latest(client):
    print "poll_latest..."

    def last_height_fetched(ec, height):
        client.fetch_block_header(height, header_fetched)

    def header_fetched(ec, header):
        print "Last:", header

    client.fetch_last_height(last_height_fetched)
    reactor.callLater(20, poll_latest, client)

Example 21

Project: bnw Source File: post.py
Function: publish
def publish(etype, *args, **kwargs):
    global listeners
    for rtype in (etype, None):
        if rtype in listeners:
            for listener in listeners[rtype].itervalues():
                reactor.callLater(0, listener, *args, **kwargs)

Example 22

Project: plugin.video.streamondemand Source File: NetBIOSProtocol.py
    def cleanupPendingTrns(self):
        now = time.time()

        # reply should have been received in the past
        expired = filter(lambda (trn_id, (expiry_time, name, d)): expiry_time < now, self.pending_trns.iteritems())

        # remove expired items from dict + call errback
        def expire_item(item):
            trn_id, (expiry_time, name, d) = item

            del self.pending_trns[trn_id]
            try:
                d.errback(NetBIOSTimeout(name))
            except: pass

        map(expire_item, expired)

        if self.transport:
            reactor.callLater(1, self.cleanupPendingTrns)

Example 23

Project: airpnp Source File: device_discovery.py
    def _msearch_discover(self, msearch):
        """Send M-SEARCH device discovery requests."""
        log.msg('Sending out M-SEARCH discovery requests', ll=3)
        ifs = [self._ip_addr]
        # send two requests to counter UDP unreliability
        reactor.callLater(0, msearch.send, reactor, 'ssdp:all', 5,
                          interfaces=ifs)
        reactor.callLater(1, msearch.send, reactor, 'ssdp:all', 5,
                          interfaces=ifs)

Example 24

Project: hubplus Source File: eventloop.py
    @effect_method
    def tick_after(self, secs):
        if self._delayed_call and self._delayed_call.active():
            self._delayed_call.reset(secs)
        else:
            print "tick : " + `secs`
            self._delayed_call = reactor.callLater(
                secs, Time.tick
                )

Example 25

Project: downpour Source File: __init__.py
    def grew(self, count):
        try:
            # This is when growLater did /not/ fire.
            self.growLater.delay(self.period)
        except:
            # This is when grow got called because of the timer
            with self.lock:
                self.growLater = reactor.callLater(self.period, self.grow, self.poolSize - self.numFlight)
        if count:
            self.serveNext()
        return count

Example 26

Project: vertex Source File: ptcp.py
    def ackSoon(self):
        """
        Emit an acknowledgement packet soon.
        """
        if self._ackTimer is None:
            def originateAck():
                self._ackTimer = None
                self.originate(ack=True)
            self._ackTimer = reactor.callLater(0.1, originateAck)
        else:
            self._ackTimer.reset(ACK_DELAY)

Example 27

Project: txAMQP Source File: test_heartbeat.py
Function: test_heartbeat
    def test_heartbeat(self):
        """
        Test that heartbeat frames are sent and received
        """
        d = Deferred()
        def checkPulse(dummy):
            self.assertTrue(self.client.called_send_hb,
                        "A heartbeat frame was recently sent")
            self.assertTrue(self.client.called_reschedule_check,
                        "A heartbeat frame was recently received")
        d.addCallback(checkPulse)
        reactor.callLater(3, d.callback, None)
        return d

Example 28

Project: pyutil Source File: twistedutil.py
def callLater_weakly(delay, func, *args, **kwargs):
    """
    Call func later, but if func is a bound method then make the reference it holds to object be a weak reference.

    Therefore, if this scheduled event is a bound method and it is the only thing keeping the object from being garbage collected, the object will be garbage collected and the event will be cancelled.
    """
    warnings.warn("deprecated", DeprecationWarning)

    def cleanup(weakmeth, thedeadweakref):
        if weakmeth.callId.active():
            weakmeth.callId.cancel()
    weakmeth = WeakMethod(func, callback=cleanup)
    weakmeth.callId = reactor.callLater(delay, weakmeth, *args, **kwargs)
    return weakmeth

Example 29

Project: awspider Source File: requestqueuer.py
Function: check_active
    def _checkActive(self):
        while self.getActive() < self.max_simul_reqs and self.getPending() > 0:     
            hosts = self.pending_reqs.keys()
            dispatched_requests = False
            for host in hosts:
                if len(self.pending_reqs[host]) == 0:
                    del self.pending_reqs[host]
                elif self._hostRequestCheck(host):
                    dispatched_requests = True
                    req = self.pending_reqs[host].pop(0)
                    d = self._getPage(req)
                    d.addCallback(self._requestComplete, req["deferred"], host)
                    d.addErrback(self._requestError, req["deferred"], host)
                    self.last_req[host] = time.time()
                    self.active_reqs[host] = self.active_reqs.get(host, 0) + 1
            if not dispatched_requests:
                break
        if self.getPending() > 0:
            reactor.callLater(.1, self._checkActive)

Example 30

Project: wokkel Source File: roster_client_versioning.py
    def connectionInitialized(self):
        RosterClientProtocol.connectionInitialized(self)
        if self.roster is not None:
            version = self.roster.version
        else:
            version = ""
        d = self.getRoster(version)
        d.addCallback(self.gotRoster)
        d.addErrback(log.err)

        reactor.callLater(15, self.xmlstream.sendFooter)

Example 31

Project: txamqp Source File: server.py
    def _dispatchWork(self, w):
        # Just assume that it may take a long time
        results = self.operations[w.op](w.num1, w.num2)
        d = defer.Deferred()
        reactor.callLater(0, d.callback, results)
        return d

Example 32

Project: txZMQ Source File: pub_sub.py
Function: publish
    def publish():
        data = str(time.time())
        print "publishing %r" % data
        s.publish(data)

        reactor.callLater(1, publish)

Example 33

Project: ZenPacks.zenoss.Microsoft.Windows Source File: twisted_utils.py
Function: sleep
def sleep(seconds):
    '''
    Return a deferred that is called in given seconds.
    '''
    d = Deferred()
    reactor.callLater(seconds, d.callback, None)
    return d

Example 34

Project: hookah Source File: dispatch.py
def if_fail(reason, url, data, retry, content_type):
    if reason.getErrorMessage()[0:3] in ['301', '302', '303']:
        return # Not really a fail
    print reason.getErrorMessage()
    if retry < RETRIES:
        retry += 1
        reactor.callLater(retry * DELAY_MULTIPLIER, post_and_retry, url, data, retry, content_type)

Example 35

Project: PiIO.WS Source File: client_protocol.py
    def poll_and_send(self):
        if self.ackcount <= -10 or self.paused:
            return

        for key, value in self.config_reads.iteritems():
            self.polldata_read[key] = value['obj'].read()
        for key, value in self.config_writes.iteritems():
            self.polldata_write[key] = value['obj'].read()

        if len(self.polldata_read) > 0 or len(self.polldata_write) > 0:
            msg = {'cmd':common_protocol.RPIClientCommands.DATA}
            msg['read'] = self.polldata_read
            msg['write'] = self.polldata_write
            self.ackcount -= 1
            self.protocol.sendMessage(json.dumps(msg))

        reactor.callLater(0, self.poll_and_send)

Example 36

Project: sstp-server Source File: sstp.py
    def pppStoped(self):
        if (self.state != SERVER_CONNECT_REQUEST_PENDING and
                self.state != SERVER_CALL_CONNECTED_PENDING and
                self.state != SERVER_CALL_CONNECTED):
            self.transport.loseConnection()
            return
        self.state = CALL_DISCONNECT_IN_PROGRESS_1
        msg = SSTPControlPacket(SSTP_MSG_CALL_DISCONNECT)
        msg.attributes = [(SSTP_ATTRIB_NO_ERROR, ATTRIB_STATUS_NO_ERROR)]
        msg.writeTo(self.transport.write)
        self.state = CALL_DISCONNECT_ACK_PENDING
        reactor.callLater(5, self.transport.loseConnection)

Example 37

Project: buildbot_travis Source File: runner.py
Function: redraw
    def redraw(self):
        # redraw with 100ms debounce
        with self.lock:
            if not self.redrawing:
                self.redrawing = True
                reactor.callLater(0.1, self._redraw)

Example 38

Project: distributed-frontera Source File: utils.py
Function: schedule
    def schedule(self, delay=0.0):
        if self._call is None:
            d = Deferred()
            d.addCallback(self)
            if self._errfunc:
                d.addErrback(self.error)
            self._call = reactor.callLater(delay, d.callback, None)

Example 39

Project: zmqproto Source File: zmqsocket.py
    def on_connection_error(self, reason):
        from twisted.internet import reactor
        print reason.getErrorMessage()
        print "Reconnect in 10 seconds..."
        reactor.callLater(10, self.connect, self.address)
        return reason

Example 40

Project: kamaelia_ Source File: RawServer_twisted.py
Function: add_task
    def add_task(self, func, delay, args=(), context=None):
        assert thread.get_ident() == self.ident
        assert type(args) == list or type(args) == tuple

        #we're going to check again later anyway
        #if self.live_contexts.has_key(context):
        reactor.callLater(delay, self.autoprune, self._make_wrapped_call,
                          func, args, context=context)

Example 41

Project: CouchPotatoServer Source File: testutil.py
    def _poll(self, res, check_f, pollinterval):
        if check_f():
            return True
        d = defer.Deferred()
        d.addCallback(self._poll, check_f, pollinterval)
        reactor.callLater(pollinterval, d.callback, None)
        return d

Example 42

Project: pixelated-user-agent Source File: test_incoming_mail.py
    def wait_in_reactor(self):
        d = defer.Deferred()

        def done_waiting():
            d.callback(None)

        reactor.callLater(1, done_waiting)
        return d

Example 43

Project: gateway Source File: broadcast.py
Function: watchdog
    def watchdog(self):
        if self.last_status + 5 < time.time():
            print "broadcaster issues!", self.issues
            self.issues += 1
        else:
            self.issues = 0
        reactor.callLater(1, self.watchdog)

Example 44

Project: deblaze Source File: test_twisted.py
Function: test_deferred_auth
    def test_deferred_auth(self):
        d = defer.Deferred()

        def auth(u, p):
            return reactor.callLater(0, lambda: True)

        gw = _twisted.TwistedGateway({'echo': lambda x: x}, authenticator=auth)
        proc = _twisted.AMF0RequestProcessor(gw)

        request = remoting.Request('echo', envelope=remoting.Envelope())

        def cb(result):
            self.assertTrue(result)
            d.callback(None)

        proc(request).addCallback(cb).addErrback(lambda failure: d.errback())

        return d

Example 45

Project: quarry Source File: tasks.py
    def add_delay(self, time, callback, *args):
        task = reactor.callLater(time, callback, *args)
        def stop():
            if task.active():
                task.cancel()
        def restart():
            if task.active():
                task.reset(time)
        task.restart = restart
        task.stop = stop
        self._tasks.append(task)
        return task

Example 46

Project: eth-proxy Source File: socket_transport.py
Function: connect
    def connect(self):
        if self.proxy:
            self.timeout_handler = reactor.callLater(60, self.connection_timeout)
            sw = sockswrapper(self.proxy, self.main_host)
            sw.connect(self)
        else:
            self.timeout_handler = reactor.callLater(30, self.connection_timeout)
            reactor.connectTCP(self.main_host[0], self.main_host[1], self)

Example 47

Project: vumi-go Source File: billing_worker.py
    @inlineCallbacks
    def _call_with_retry(self, url, data, headers, method):
        """
        Make an HTTP request and retry after a delay if it raises an exception.
        """
        try:
            response = yield http_request_full(
                url, data, headers=headers, method=method)
        except Exception:
            # Wait a bit and then retry. Only one retry here.
            d = Deferred()
            reactor.callLater(self.retry_delay, d.callback, None)
            yield d
            response = yield http_request_full(
                url, data, headers=headers, method=method)
        returnValue(response)

Example 48

Project: pyGBot Source File: Log2channel.py
    def _queueSchedule(self):
        """ Schedule the next message to send from the queue. """
        if self._queue:
            if self._queueEmptying:
                # schedule only if existing call has already been executed
                if not self._queueEmptying.active():
                    reactor.callLater(self._serialDelay, self._queueSend)
            else:
                reactor.callLater(self._initialDelay, self._queueSend)
        else:
            self._queueEmptying = None

Example 49

Project: txstatsd Source File: router.py
Function: build_protocol
    def buildProtocol(self, addr):
        from twisted.internet import reactor

        self.resetDelay()
        self.protocol = TCPRedirectProtocol()
        if self.callback:
            reactor.callLater(0, self.callback)
            self.callback = None

        return self.protocol

Example 50

Project: imaginary Source File: test_mice.py
    def test_mouseActivation(self):
        """
        Activating a mouse should set the scheduling mechanism to the
        reactor's.
        """
        from twisted.internet import reactor
        self.assertEquals(self.mousehood._callLater, reactor.callLater)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4