当前位置: 首页>>代码示例>>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;未经允许,请勿转载。