當前位置: 首頁>>代碼示例>>Python>>正文


Python reactor.callLater方法代碼示例

本文整理匯總了Python中twisted.internet.reactor.callLater方法的典型用法代碼示例。如果您正苦於以下問題:Python reactor.callLater方法的具體用法?Python reactor.callLater怎麽用?Python reactor.callLater使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在twisted.internet.reactor的用法示例。


在下文中一共展示了reactor.callLater方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def __init__(self, stealStdio=True, printToConsole=True):
        '''
        The one big thing this function leaves out is reactor.start(). Call this externally
        *after * initializing a nexus object.
        '''
        self.session = None
        self.wamp_connected = False
        self.jwt_valid = False

        self.info = AttrWrapper()
        resolveInfo(self, settings.CONFIG_FILE)
        self.info.setOnChange(self.onInfoChange)

        # initialize output. If filepath is set, logs to file.
        # If stealStdio is set intercepts all stderr and stdout and interprets it internally
        # If printToConsole is set (defaults True) all final output is rendered to stdout
        output.out.startLogging(filePath=settings.LOG_DIR, stealStdio=stealStdio, printToConsole=printToConsole)

        # register onStop for the shutdown call
        reactor.addSystemEventTrigger('before', 'shutdown', self.onStop)

        # The reactor needs to be runnnig before this call is fired, since we start the session
        # here. Assuming callLater doesn't fire until thats happened
        reactor.callLater(0, self.onStart) 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:26,代碼來源:nexus.py

示例2: test_catalog

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def test_catalog(self, consul_port):
        c = consul.twisted.Consul(port=consul_port)

        @defer.inlineCallbacks
        def register():
            response = yield c.catalog.register('n1', '10.1.10.11')
            assert response is True
            yield sleep(50 / 1000.0)
            response = yield c.catalog.deregister('n1')
            assert response is True

        reactor.callLater(1.0 / 100, register)

        index, nodes = yield c.catalog.nodes()
        assert len(nodes) == 1
        current = nodes[0]

        index, nodes = yield c.catalog.nodes(index=index)
        nodes.remove(current)
        assert [x['Node'] for x in nodes] == ['n1']

        index, nodes = yield c.catalog.nodes(index=index)
        nodes.remove(current)
        assert [x['Node'] for x in nodes] == [] 
開發者ID:poppyred,項目名稱:python-consul2,代碼行數:26,代碼來源:test_twisted.py

示例3: connect

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def connect(self, reconnecting=False):
        if self.connecting and not reconnecting:
            return
        self.connecting = True
        end_point = TCP4ClientEndpoint(reactor, self.host, self.port, 10)
        d = end_point.connect(Factory.forProtocol(GraphiteProtocol))

        def success(connection):
            self.connecting = False
            log.info('Connected to {replica}', replica=self)
            self.connection = connection

        def failed(error):
            log.error('Connect to {replica} failed: {error}', replica=self, error=error)
            reactor.callLater(10, self.connect, True)
        d.addCallbacks(success, failed) 
開發者ID:moira-alert,項目名稱:worker,代碼行數:18,代碼來源:graphite.py

示例4: play

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def play(self, client, param, tab = -1):
        if param[0] == 'ir' and (self.tabMatch is None or not self.tabMatch.battleStarted):
            moveSpins = ','.join(map(str, self.moveSpins))
            for p in self:
                pCards = ''
                if p in self.Playing:
                    pCards = ','.join(map(str, map(int, self.Playing[self.Playing.index(p)].deck)))
                p.send('zm', 'nt', self.slotPlayer.index, moveSpins, pCards)

            self.boardTimeoutHandler = reactor.callLater(22, self.checkGameStatus)
        else:
            gameStatus = super(CardJitsuFireSenseiGame, self).play(client, param, tab)

        if param[0] == 'ir' and gameStatus:
            if self.tabPlayer == self.Playing[0]:  # sensei
                self.checkGameStatus()

        if param[0] == 'cc' and gameStatus:
            self.checkBattleStatus(True) 
開發者ID:Times-0,項目名稱:Timeline,代碼行數:21,代碼來源:Sensei.py

示例5: _connect_to_management

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def _connect_to_management(self, retries=30):
        if retries == 0:
            self.log.error('Timeout while connecting to management')
            self.failed = True
            return

        def retry(retries):
            ctr = retries - 1
            self.log.warn(
                'Error connecting to management, retrying. '
                'Retries left:  %s' % ctr)
            reactor.callLater(
                0.1, self._connect_to_management, ctr)

        self._d = connectProtocol(
            self._management_endpoint,
            ManagementProtocol(verbose=True))
        self._d.addCallbacks(
            self._got_management_protocol,
            lambda f: retry(retries)) 
開發者ID:leapcode,項目名稱:bitmask-dev,代碼行數:22,代碼來源:process.py

示例6: getReply

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def getReply(self, line, proto, transport):
        proto.lineReceived(line)

        if line[:4] not in ['HELO', 'MAIL', 'RCPT', 'DATA']:
            return succeed("")

        def check_transport(_):
            reply = transport.value()
            if reply:
                transport.clear()
                return succeed(reply)

            d = Deferred()
            d.addCallback(check_transport)
            reactor.callLater(0, lambda: d.callback(None))
            return d

        return check_transport(None) 
開發者ID:leapcode,項目名稱:bitmask-dev,代碼行數:20,代碼來源:test_gateway.py

示例7: onSessionOpen

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def onSessionOpen(self):

        self.prefix("broadcast", "de.elmyra.kotori.broadcast")
        self.prefix("presence", "http://kotori.elmyra.de/presence?")
        self.prefix("node", "http://kotori.elmyra.de/node/{0}#".format(NODE_ID))

        self.subscribe("broadcast:node-heartbeat", self.dump_event)

        self.subscribe("presence:node_id={0}&hostname={1}".format(NODE_ID, NODE_HOSTNAME), lambda: x)

        self.subscribe("node:say", self.dump_event)
        self.subscribe("node:say", self.say)

        print "INFO:   -> Node successfully connected to master"

        self.heartbeat()

        reactor.callLater(0, node_manager.start_features, self) 
開發者ID:daq-tools,項目名稱:kotori,代碼行數:20,代碼來源:nodeservice.py

示例8: boot_node

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def boot_node(websocket_uri, debug=False, trace=False):

    print 'INFO: Starting node service, connecting to', websocket_uri

    # connect to master service
    """
    global node_manager
    node_manager = NodeManager(websocket_uri, debug=debug)
    reactor.callLater(0, node_manager.master_connect)
    """

    runner = ApplicationRunner(websocket_uri, u'kotori-realm', debug=trace, debug_wamp=debug, debug_app=debug)
    runner.run(KotoriNode, start_reactor=False)

    #app = Application()
    #app.run(url=websocket_uri, realm='kotori-realm', debug=True, debug_wamp=True, debug_app=True, start_reactor=False) 
開發者ID:daq-tools,項目名稱:kotori,代碼行數:18,代碼來源:nodeservice.py

示例9: connectionMade

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def connectionMade(self):
        """Override BaseProtocol.connectionMade."""
        def forward_connection(_result):
            """Callback for startup_commands."""
            exchange.client_connected(self.handle, self)
            # noinspection PyUnresolvedReferences
            self.ping_timer = reactor.callLater(
                self.factory.ping_interval, self.ping)

        def kill_connection(error):
            """Errback for startup_commands."""
            LOG.e("Error: Could not send the startup functions to the client:",
                  error)
            self._loseConnection()

        peer = self.transport.getPeer()
        self.handle = "{}:{}".format(peer.host, peer.port)
        LOG.w("Connected:", self.handle)
        dfr = self.command(self.factory.startup_commands)
        dfr.addCallback(forward_connection)
        dfr.addErrback(kill_connection) 
開發者ID:epoptes,項目名稱:epoptes,代碼行數:23,代碼來源:bashplex.py

示例10: circuitCompleted

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def circuitCompleted(self, conn_to_flush):
        """
        Circuit was just completed; that is, its endpoints are now
        connected. Do all the things we have to do now.
        """
        if self.closed:
            log.debug("%s: Completed circuit while closed. Ignoring.", self.name)
            return

        log.debug("%s: Circuit completed." % self.name)

        # Set us as the circuit of our pluggable transport instance.
        self.transport.circuit = self

        # Call the transport-specific circuitConnected method since
        # this is a good time to perform a handshake.
        self.transport.circuitConnected()

        # Do a dummy dataReceived on the initiating connection in case
        # it has any buffered data that must be flushed to the network.
        #
        # (We use callLater because we want to return back to the
        # event loop so that any messages we send in circuitConnected get sent
        # to the network immediately.)
        reactor.callLater(0.01, conn_to_flush.dataReceived, '') 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:27,代碼來源:network.py

示例11: _putConnection

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def _putConnection(self, key, connection):
        """
        Return a persistent connection to the pool. This will be called by
        L{HTTP11ClientProtocol} when the connection becomes quiescent.
        """
        if connection.state != "QUIESCENT":
            # Log with traceback for debugging purposes:
            try:
                raise RuntimeError(
                    "BUG: Non-quiescent protocol added to connection pool.")
            except:
                log.err()
            return
        connections = self._connections.setdefault(key, [])
        if len(connections) == self.maxPersistentPerHost:
            dropped = connections.pop(0)
            dropped.transport.loseConnection()
            self._timeouts[dropped].cancel()
            del self._timeouts[dropped]
        connections.append(connection)
        cid = self._reactor.callLater(self.cachedConnectionTimeout,
                                      self._removeConnection,
                                      key, connection)
        self._timeouts[connection] = cid 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:26,代碼來源:client.py

示例12: test_lateCompletionWorks

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def test_lateCompletionWorks(self):
        """
        L{H2Connection} correctly unblocks when a stream is ended.
        """
        connection = H2Connection()
        connection.requestFactory = DelayedHTTPHandler
        _, transport = self.connectAndReceive(
            connection, self.getRequestHeaders, []
        )

        # Delay a call to end request, forcing the connection to block because
        # it has no data to send.
        request = connection.streams[1]._request
        reactor.callLater(0.01, request.finish)

        def validateComplete(*args):
            frames = framesFromBytes(transport.value())

            # Check that the stream is correctly terminated.
            self.assertEqual(len(frames), 3)
            self.assertTrue('END_STREAM' in frames[-1].flags)

        return connection._streamCleanupCallbacks[1].addCallback(
            validateComplete
        ) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:27,代碼來源:test_http2.py

示例13: test_cantRegisterAfterRun

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def test_cantRegisterAfterRun(self):
        """
        It is not possible to register a C{Application} after the reactor has
        already started.
        """
        reactor = gireactor.GIReactor(useGtk=False)
        self.addCleanup(self.unbuildReactor, reactor)
        app = Gio.Application(
            application_id='com.twistedmatrix.trial.gireactor',
            flags=Gio.ApplicationFlags.FLAGS_NONE)

        def tryRegister():
            exc = self.assertRaises(ReactorAlreadyRunning,
                                    reactor.registerGApplication, app)
            self.assertEqual(exc.args[0],
                             "Can't register application after reactor was started.")
            reactor.stop()
        reactor.callLater(0, tryRegister)
        ReactorBuilder.runReactor(self, reactor) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:21,代碼來源:test_gireactor.py

示例14: test_noAutoAddSubdirectory

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def test_noAutoAddSubdirectory(self):
        """
        L{inotify.INotify.watch} with autoAdd==False will stop inotify
        from watching subdirectories created under the watched one.
        """
        def _callback(wp, fp, mask):
            # We are notified before we actually process new
            # directories, so we need to defer this check.
            def _():
                try:
                    self.assertFalse(self.inotify._isWatched(subdir))
                    d.callback(None)
                except Exception:
                    d.errback()
            reactor.callLater(0, _)

        checkMask = inotify.IN_ISDIR | inotify.IN_CREATE
        self.inotify.watch(
            self.dirname, mask=checkMask, autoAdd=False,
            callbacks=[_callback])
        subdir = self.dirname.child('test')
        d = defer.Deferred()
        subdir.createDirectory()
        return d 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:26,代碼來源:test_inotify.py

示例15: send

# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import callLater [as 別名]
def send(self, report):
        request = PDServerRequest('/api/routers/{router_id}/' + self.model)
        d = request.post(**report)

        # Check for error code and retry.
        def cbresponse(response):
            if not response.success:
                out.warn('{} to {} returned code {}'.format(request.method,
                    request.url, response.code))
                if self.max_retries is None or self.retries < self.max_retries:
                    reactor.callLater(self.retryDelay, self.send, report)
                    self.retries += 1
                    self.increaseDelay()
                nexus.core.jwt_valid = False
            else:
                nexus.core.jwt_valid = True

        # Check for connection failures and retry.
        def cberror(ignored):
            out.warn('{} to {} failed'.format(request.method, request.url))
            if self.max_retries is None or self.retries < self.max_retries:
                reactor.callLater(self.retryDelay, self.send, report)
                self.retries += 1
                self.increaseDelay()
            nexus.core.jwt_valid = False

        d.addCallback(cbresponse)
        d.addErrback(cberror)
        return d 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:31,代碼來源:reporting.py


注:本文中的twisted.internet.reactor.callLater方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。