当前位置: 首页>>代码示例>>Python>>正文


Python task.deferLater方法代码示例

本文整理汇总了Python中twisted.internet.task.deferLater方法的典型用法代码示例。如果您正苦于以下问题:Python task.deferLater方法的具体用法?Python task.deferLater怎么用?Python task.deferLater使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.internet.task的用法示例。


在下文中一共展示了task.deferLater方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: acquireTriggerCheckLock

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def acquireTriggerCheckLock(self, trigger_id, timeout):
        """
        acquireTriggerCheckLock(self, trigger_id, timeout)

        Try to acquire lock for trigger check until timeout

        :param trigger_id: trigger identity
        :type trigger_id: string
        :param timeout: timeout in seconds
        :type timeout: float
        """
        acquired = yield self.setTriggerCheckLock(trigger_id)
        count = 0
        while acquired is None and count < timeout:
            count += 1
            yield task.deferLater(reactor, 0.5, lambda: None)
            acquired = yield self.setTriggerCheckLock(trigger_id)
        if acquired is None:
            raise Exception("Can not acquire trigger lock in {0} seconds".format(timeout)) 
开发者ID:moira-alert,项目名称:worker,代码行数:21,代码来源:db.py

示例2: perform

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def perform(self):
        try:
            trigger_id = yield self.db.getTriggerToCheck()
            while trigger_id is not None:
                acquired = yield self.db.setTriggerCheckLock(trigger_id)
                if acquired is not None:
                    start = reactor.seconds()
                    trigger = Trigger(trigger_id, self.db)
                    yield trigger.check()
                    end = reactor.seconds()
                    yield self.db.delTriggerCheckLock(trigger_id)
                    spy.TRIGGER_CHECK.report(end - start)
                trigger_id = yield self.db.getTriggerToCheck()
            yield task.deferLater(reactor, random.uniform(PERFORM_INTERVAL * 10, PERFORM_INTERVAL * 20), lambda: None)
        except GeneratorExit:
            pass
        except Exception as e:
            spy.TRIGGER_CHECK_ERRORS.report(0)
            log.error("Failed to perform triggers check: {e}", e=e)
            yield task.deferLater(reactor, ERROR_TIMEOUT, lambda: None) 
开发者ID:moira-alert,项目名称:worker,代码行数:22,代码来源:worker.py

示例3: _loopbackAsyncContinue

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def _loopbackAsyncContinue(ignored, server, serverToClient, client,
                           clientToServer, pumpPolicy):
    # Clear the Deferred from each message queue, since it has already fired
    # and cannot be used again.
    clientToServer._notificationDeferred = None
    serverToClient._notificationDeferred = None

    # Schedule some more byte-pushing to happen.  This isn't done
    # synchronously because no actual transport can re-enter dataReceived as
    # a result of calling write, and doing this synchronously could result
    # in that.
    from twisted.internet import reactor
    return deferLater(
        reactor, 0,
        _loopbackAsyncBody,
        server, serverToClient, client, clientToServer, pumpPolicy) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:18,代码来源:loopback.py

示例4: test_cancel

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def test_cancel(self):
        """
        The L{Deferred} returned by L{task.deferLater} can be
        cancelled to prevent the call from actually being performed.
        """
        called = []
        clock = task.Clock()
        d = task.deferLater(clock, 1, called.append, None)
        d.cancel()
        def cbCancelled(ignored):
            # Make sure there are no calls outstanding.
            self.assertEqual([], clock.getDelayedCalls())
            # And make sure the call didn't somehow happen already.
            self.assertFalse(called)
        self.assertFailure(d, defer.CancelledError)
        d.addCallback(cbCancelled)
        return d 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:19,代码来源:test_task.py

示例5: stopListening

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def stopListening(self):
        """
        Stop accepting connections on this port.

        This will shut down my socket and call self.connectionLost().

        @return: A L{Deferred} that fires when this port has stopped.
        """
        self.stopReading()
        if self.disconnecting:
            return self._stoppedDeferred
        elif self.connected:
            self._stoppedDeferred = task.deferLater(
                self.reactor, 0, self.connectionLost)
            self.disconnecting = True
            return self._stoppedDeferred
        else:
            return defer.succeed(None) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:20,代码来源:tuntap.py

示例6: test_reserve_uid_timeout

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def test_reserve_uid_timeout(self):
        # WARNING: This test is fundamentally flawed and will fail
        # intermittently because it uses the real clock.
        uid = "test-test-test"
        from twistedcaldav.config import config
        old_timeout = config.UIDReservationTimeOut
        config.UIDReservationTimeOut = 1

        def _finally():
            config.UIDReservationTimeOut = old_timeout

        d = self.db.isReservedUID(uid)
        d.addCallback(self.assertFalse)
        d.addCallback(lambda _: self.db.reserveUID(uid))
        d.addCallback(lambda _: self.db.isReservedUID(uid))
        d.addCallback(self.assertTrue)
        d.addCallback(lambda _: deferLater(reactor, 2, lambda: None))
        d.addCallback(lambda _: self.db.isReservedUID(uid))
        d.addCallback(self.assertFalse)
        self.addCleanup(_finally)

        return d 
开发者ID:apple,项目名称:ccs-calendarserver,代码行数:24,代码来源:test_index_file.py

示例7: testTimeout_betweenRequests

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def testTimeout_betweenRequests(self):
        cxn = self.connect(betweenRequestsTimeOut=0.3)
        cmds = [[]]
        data = ""

        cxn.client.write("GET / HTTP/1.1\r\n\r\n")
        cmds[0] += [('init', 'GET', '/', (1, 1), 0, ()),
                    ('contentComplete',)]
        self.compareResult(cxn, cmds, data)

        response = TestResponse()
        response.headers.setRawHeaders("Content-Length", ("0",))
        cxn.requests[0].writeResponse(response)
        response.finish()

        data += "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"

        self.compareResult(cxn, cmds, data)
        return deferLater(reactor, 0.5, self.assertDone, cxn)  # Wait for timeout 
开发者ID:apple,项目名称:ccs-calendarserver,代码行数:21,代码来源:test_http.py

示例8: testTimeout_abortRequest

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def testTimeout_abortRequest(self):
        cxn = self.connect(allowPersistentConnections=False, closeTimeOut=0.3)
        cxn.client.transport.loseConnection = lambda: None
        cmds = [[]]
        data = ""

        cxn.client.write("GET / HTTP/1.1\r\n\r\n")
        cmds[0] += [('init', 'GET', '/', (1, 1), 0, ()),
                    ('contentComplete',)]
        self.compareResult(cxn, cmds, data)

        response = TestResponse()
        response.headers.setRawHeaders("Content-Length", ("0",))
        cxn.requests[0].writeResponse(response)
        response.finish()

        data += "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"

        self.compareResult(cxn, cmds, data)

        def _check(cxn):
            self.assertDone(cxn)
            self.assertTrue(cxn.serverToClient.aborted)
        return deferLater(reactor, 0.5, self.assertDone, cxn)  # Wait for timeout 
开发者ID:apple,项目名称:ccs-calendarserver,代码行数:26,代码来源:test_http.py

示例9: __attrs_post_init__

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def __attrs_post_init__(self):
        self._have_made_a_successful_connection = False
        self._stopping = False

        self._trace = None
        self._ws = None
        f = WSFactory(self, self._url)
        f.setProtocolOptions(autoPingInterval=60, autoPingTimeout=600)
        ep = self._make_endpoint(self._url)
        self._connector = internet.ClientService(ep, f)
        faf = None if self._have_made_a_successful_connection else 1
        d = self._connector.whenConnected(failAfterFailures=faf)
        # if the initial connection fails, signal an error and shut down. do
        # this in a different reactor turn to avoid some hazards
        d.addBoth(lambda res: task.deferLater(self._reactor, 0.0, lambda: res))
        # TODO: use EventualQueue
        d.addErrback(self._initial_connection_failed)
        self._debug_record_inbound_f = None 
开发者ID:warner,项目名称:magic-wormhole,代码行数:20,代码来源:_rendezvous.py

示例10: render_GET

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def render_GET(self, request):
        """ handles get requests for metrics, health, and everything else """
        path = request.path.decode()
        request.setHeader("Content-Type", "text/plain; charset=UTF-8")
        if path == '/metrics':
            deferred_request = deferLater(reactor, 0, lambda: request)
            deferred_request.addCallback(self.generate_latest_metrics)
            deferred_request.addErrback(self.errback, request)
            return NOT_DONE_YET
        elif path == '/healthz':
            request.setResponseCode(200)
            log("Service is UP")
            return 'Server is UP'.encode()
        else:
            log("Uri not found: " + request.uri)
            request.setResponseCode(404)
            return '404 Not Found'.encode() 
开发者ID:rverchere,项目名称:vmware_exporter,代码行数:19,代码来源:vmware_exporter.py

示例11: startProtocol

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def startProtocol(self):
        """
        Join the multicast group and announce the identity
        and decide to become the leader if there is no response
        """
        self.book.peers[self.book.uuidObj] = self._addr
        # datagrams can traverse more than one router hop
        self.transport.setTTL(5)
        self.transport.joinGroup(MCAST_ADDR[0])
        self._broadcast_identity()
        self.log.msg('joining the multicast group and waiting for response')
        wait_for_response = 3

        def response_from_peers():
            self._eid = self.generate_election_id()
            self.log.msg('Announcing itself as the winner')
            self._leader(leader=self.book.uuidObj, eid=self._eid)

        self._npCallId = task.deferLater(
            reactor,
            wait_for_response,
            response_from_peers)
        self.d = threads.deferToThread(self._poll) 
开发者ID:nirvik,项目名称:iWant,代码行数:25,代码来源:beacon.py

示例12: _broadcast_re_election

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def _broadcast_re_election(self):
        def election_timeout_callback():
            eid = self.generate_election_id()
            self.log.msg('broadcast re-election id {0}'.format(eid))
            msg = bake(RE_ELECTION, election_id=eid)
            self.send(msg, MCAST_ADDR)
        if self._reelectionClock is None:
            self._reelectionClock = reactor
        election_timeout = self.generate_timeout()
        self.log.msg('{0} timeout: ECommencement msg'.format(election_timeout))
        # print '{0} timeout: ECommencement msg'.format(election_timeout)
        # broadcast relection can be called twice if leader announces its death
        # and polling also determines leaders death
        self.cancel_election_commencement_callback()
        self._reelectionCallId = task.deferLater(
            reactor,
            election_timeout,
            election_timeout_callback) 
开发者ID:nirvik,项目名称:iWant,代码行数:20,代码来源:beacon.py

示例13: test_callback

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def test_callback(self):
        """
        The L{Deferred} returned by L{task.deferLater} is called back after
        the specified delay with the result of the function passed in.
        """
        results = []
        flag = object()
        def callable(foo, bar):
            results.append((foo, bar))
            return flag

        clock = task.Clock()
        d = task.deferLater(clock, 3, callable, 'foo', bar='bar')
        d.addCallback(self.assertIdentical, flag)
        clock.advance(2)
        self.assertEqual(results, [])
        clock.advance(1)
        self.assertEqual(results, [('foo', 'bar')])
        return d 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:21,代码来源:test_task.py

示例14: unconfirm_callback

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def unconfirm_callback(self, txd, txid):
        #find the offer for this tx
        offerinfo = self.tx_match(txd)
        if not offerinfo:
            return False
        to_cancel, to_announce = self.client.on_tx_unconfirmed(offerinfo,
                                                               txid)
        self.client.modify_orders(to_cancel, to_announce)

        txinfo = tuple((x["script"], x["value"]) for x in txd["outs"])
        confirm_timeout_sec = float(jm_single().config.get(
            "TIMEOUT", "confirm_timeout_hours")) * 3600
        task.deferLater(reactor, confirm_timeout_sec,
                        self.client.wallet_service.check_callback_called,
                        txinfo, self.confirm_callback, "confirmed",
        "transaction with outputs " + str(txinfo) + " not confirmed.")

        d = self.callRemote(commands.JMAnnounceOffers,
                            to_announce=json.dumps(to_announce),
                            to_cancel=json.dumps(to_cancel),
                            offerlist=json.dumps(self.client.offerlist))
        self.defaultCallbacks(d)
        return True 
开发者ID:JoinMarket-Org,项目名称:joinmarket-clientserver,代码行数:25,代码来源:client_protocol.py

示例15: restart

# 需要导入模块: from twisted.internet import task [as 别名]
# 或者: from twisted.internet.task import deferLater [as 别名]
def restart(self):
        from twisted.internet import reactor

        log.debug("Restarting %s client...", self.name)
        if self.state in (Tahoe.STOPPING, Tahoe.STARTING):
            log.warning(
                "Aborting restart operation; "
                'the "%s" client is already (re)starting',
                self.name,
            )
            return
        # Temporarily disable desktop notifications for (dis)connect events
        pref = get_preference("notifications", "connection")
        set_preference("notifications", "connection", "false")
        yield self.stop()
        if sys.platform == "win32":
            yield deferLater(reactor, 0.1, lambda: None)
            self._win32_cleanup()
        yield self.start()
        yield self.await_ready()
        yield deferLater(reactor, 1, lambda: None)
        set_preference("notifications", "connection", pref)
        log.debug("Finished restarting %s client.", self.name) 
开发者ID:gridsync,项目名称:gridsync,代码行数:25,代码来源:tahoe.py


注:本文中的twisted.internet.task.deferLater方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。