Python源码示例:twisted.internet.reactor.callLater()
示例1
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)
示例2
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] == []
示例3
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)
示例4
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)
示例5
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))
示例6
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)
示例7
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)
示例8
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)
示例9
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)
示例10
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, '')
示例11
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
示例12
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
)
示例13
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)
示例14
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
示例15
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
示例16
def send(self, report):
request = PDServerRequest('/api/routers/{router_id}')
d = request.patch(*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
示例17
def sleep(seconds):
"""
An asynchronous sleep function using twsited. Source:
http://twistedmatrix.com/pipermail/twisted-python/2009-October/020788.html
:type seconds: float
"""
d = defer.Deferred()
reactor.callLater(seconds, d.callback, seconds)
return d
示例18
def sleep(seconds):
"""
An asynchronous sleep function using twsited. Source:
http://twistedmatrix.com/pipermail/twisted-python/2009-October/020788.html
:type seconds: float
"""
d = defer.Deferred()
reactor.callLater(seconds, d.callback, seconds)
return d
示例19
def test_kv_missing(self, consul_port):
c = consul.twisted.Consul(port=consul_port)
reactor.callLater(2.0 / 100, c.kv.put, 'foo', 'bar')
yield c.kv.put('index', 'bump')
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')
示例20
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')
示例21
def sleep(secs):
d = defer.Deferred()
reactor.callLater(secs, d.callback, None)
return d
示例22
def sleep(secs):
d = defer.Deferred()
reactor.callLater(secs, d.callback, None)
return d
示例23
def timeout(self, delay, callback):
reactor.callLater(delay, callback)
示例24
def timeout(self, delay, callback):
reactor.callLater(delay, callback)
示例25
def handleJoinGame(client, data):
if client['room'] is not None and isinstance(client['room'], Multiplayer):
client.send('jx', client['room'].ext_id)
#reactor.callLater(4, lambda *x:client['game'].getGame(client)) # client takes time to load
示例26
def startBattle(self):
battleType = self.tabMatch.battle
if len(self.tabMatch.players) > 1:
battleType = self.tabMatch.battle = 'be'
self.tabMatch.resetBattleType = True
symbol = self.tabMatch.symbol
isCJMatch = battleType == 'be'
if not isCJMatch:
self.tabMatch.battlers = list(self.Playing)
battlingPlayers = ','.join(map(lambda x: str(x.index), self.tabMatch.battlers))
client = self.tabMatch.player
if not isCJMatch and symbol == 'n':
return client.send('zm', 'ct')
if isCJMatch and len(self.tabMatch.battlers) < 1:
availableOpponents = ','.join(map(lambda x: str(x.index), [_ for _ in (self.Playing if len(self.tabMatch.players) < 2 else self.tabMatch.players) if _ is not client]))
return client.send('zm', 'co', availableOpponents)
self.tabMatch.battleStarted = True
if self.boardTimeoutHandler is not None:
self.boardTimeoutHandler.cancel()
self.boardTimeoutHandler = None
self.battleTimeoutHandler = reactor.callLater(22, self.checkBattleStatus)
self.send('zm', 'sb', battleType, battlingPlayers, symbol)
示例27
def startGame(self):
if self.GameStarted:
return
self.noPlaying = CJ_MATS[self.waddle]
self.Playing = self[:self.noPlaying]
self.GameStarted = True
self.GameCards = [None] * self.noPlaying
self.GameDeck = [None] * self.noPlaying
self.GameBoard = map(Tile, range(self.MAX_BOARD_SPACES))
self.moveSpins = [-1, -1, -1]
self.setupCards()
self.setupBattleArena()
self.Playing = map(lambda i: CJFirePlayer(self.Playing[i], i, 6, 0, self.GameCards[i], self.GameDeck[i]), range(len(self.Playing)))
self.slotPlayer = self.Playing[0]
self.tabPlayer = self.Playing[0]
self.tabMatch = None
self.setupBoardPosition()
self.sendStartGameMessage()
self.boardTimeoutHandler = reactor.callLater(22, self.checkGameStatus)
self.battleTimeoutHandler = None
示例28
def broadcastMusic(self, nextMusic = False):
if self.broadcasting and not nextMusic:
return 0
if self.currentMusic is not None:
self.currentMusic.shared = False
self.shareQueue.remove(self.currentMusic)
if len(self.shareQueue) < 1: # try once
self.currentMusic = None
self.broadcasting = False
GeneralEvent('music:broadcast', self, None)
self.redis.server.set('music:broadcasting', None)
return 0 # No more queue
self.broadcasting = True
self.currentMusic = self.shareQueue[0]
self.redis.server.hmset('music:sharing', {self.currentMusic.id : int(0)})
t = ceil(self.currentMusic.length / 1000)
self.redis.server.set('music:broadcasting', int(self.currentMusic))
GeneralEvent('music:broadcast', self, self.currentMusic)
self.logger.info('Broadcasting "%s" by %s, %i seconds until next music!', self.currentMusic.name, self.currentMusic.pengNick, t)
self.broadcastDefer = reactor.callLater(t, self.broadcastMusic, True)
self.refresh()
示例29
def odds(self, channel, temp_time):
reactor.callLater(0, self.msg, channel, "3")
reactor.callLater(1, self.msg, channel, "2")
reactor.callLater(2, self.msg, channel, "1")
reactor.callLater(3, self.msg, channel, "GO!")
temp_time = time.time()
return
示例30
def paintMessage(self, message):
if self.painting:
return
numSeconds = 0
reactor.callLater(numSeconds, self.enablePainting)
for msg in message:
reactor.callLater(numSeconds, self.printDelayedMessage, msg)
numSeconds += 2
reactor.callLater(numSeconds, self.printDelayedMessage, self.getQuote())
reactor.callLater(numSeconds, self.disablePainting)