本文整理汇总了Python中twisted.internet.task.LoopingCall.clock方法的典型用法代码示例。如果您正苦于以下问题:Python LoopingCall.clock方法的具体用法?Python LoopingCall.clock怎么用?Python LoopingCall.clock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.task.LoopingCall
的用法示例。
在下文中一共展示了LoopingCall.clock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _startReapingProcesses
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def _startReapingProcesses(self):
"""
Start a LoopingCall that calls reapAllProcesses.
"""
lc = LoopingCall(self._reapAllProcesses)
lc.clock = self._reactor
lc.start(0.1, False)
示例2: wait_for_volume
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def wait_for_volume(self, name):
"""
Wait for a volume by the given name, owned by thus service, to exist.
Polls the storage pool for the specified volume to appear.
:param VolumeName name: The name of the volume.
:return: A ``Deferred`` that fires with a :class:`Volume`.
"""
# Change this to not create the Volume instance right away. Instead,
# try to find it by uuid/name in `check_for_volume`. If a Volume
# instance there matches, use that object as the final result of the
# Deferred returned by this method (it will have its other attributes
# set correctly because they will be set correctly by enumerate).
# FLOC-976
volume = Volume(uuid=self.uuid, name=name, service=self)
def check_for_volume(volumes):
if volume in volumes:
call.stop()
def loop():
d = self.enumerate()
d.addCallback(check_for_volume)
return d
call = LoopingCall(loop)
call.clock = self._reactor
d = call.start(WAIT_FOR_VOLUME_INTERVAL)
d.addCallback(lambda _: volume)
return d
示例3: wait_for_volume
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def wait_for_volume(self, name):
"""
Wait for a volume by the given name, owned by thus service, to exist.
Polls the storage pool for the specified volume to appear.
:param unicode name: The name of the volume.
:return: A ``Deferred`` that fires with a :class:`Volume`.
"""
volume = Volume(uuid=self.uuid, name=name, _pool=self._pool)
def check_for_volume(volumes):
if volume in volumes:
call.stop()
def loop():
d = self.enumerate()
d.addCallback(check_for_volume)
return d
call = LoopingCall(loop)
call.clock = self._reactor
d = call.start(WAIT_FOR_VOLUME_INTERVAL)
d.addCallback(lambda _: volume)
return d
示例4: make_lc
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def make_lc(self, reactor, func):
if DEBUG:
self.stdout_length = 0
self.stderr_length = 0
def _(lc, reactor):
if DEBUG:
stdout = self.stdout.getvalue()
stderr = self.stderr.getvalue()
if self.stdout.getvalue()[self.stdout_length:]:
print(self.stdout.getvalue()[self.stdout_length:],
file=sys.__stdout__)
if self.stderr.getvalue()[self.stderr_length:]:
print(self.stderr.getvalue()[self.stderr_length:],
file=sys.__stderr__)
self.stdout_length = len(stdout)
self.stderr_length = len(stderr)
return func(lc, reactor)
lc = LoopingCall(_)
lc.a = (lc, reactor)
lc.clock = reactor
lc.start(0.1)
return lc
示例5: schedule
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def schedule(self, function, interval):
"""
Schedule C{function} to be called every C{interval}
"""
task = LoopingCall(function)
if self.clock is not None:
task.clock = self.clock
self.tasks.append((task, interval))
if self.running:
task.start(interval, now=True)
示例6: add_update_loop
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def add_update_loop(self):
"""
Setup the LoopingCall to poll Consul every ``self.poll_interval``;
helper for testing.
"""
l = LoopingCall(self.update_active_node)
l.clock = self.reactor
logger.warning('Setting Consul poll interval to %s seconds',
self.poll_interval)
l.start(self.poll_interval)
示例7: wait_for_active
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def wait_for_active(log,
server_endpoint,
auth_token,
server_id,
interval=5,
clock=None):
"""
Wait until the server specified by server_id's status is 'ACTIVE'
@TODO: Timeouts
:param log: A bound logger.
:param str server_endpoint: Server endpoint URI.
:param str auth_token: Keystone Auth token.
:param str server_id: Opaque nova server id.
:param str expected_status: Nova status string.
:param int interval: Polling interval. Default: 5.
:return: Deferred that fires when the expected status has been seen.
"""
log.msg("Checking instance status every {interval} seconds",
interval=interval)
d = Deferred()
def poll():
def check_status(server):
status = server['server']['status']
log.msg("Waiting for 'ACTIVE' got {status}.", status=status)
if server['server']['status'] == 'ACTIVE':
d.callback(server)
elif server['server']['status'] != 'BUILDING':
d.errback(UnexpectedServerStatus(
server_id,
status,
'ACTIVE'))
sd = server_details(server_endpoint, auth_token, server_id)
sd.addCallback(check_status)
return sd
lc = LoopingCall(poll)
if clock is not None: # pragma: no cover
lc.clock = clock
def stop(r):
lc.stop()
return r
d.addBoth(stop)
return lc.start(interval).addCallback(lambda _: d)
示例8: createExpirationChecker
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def createExpirationChecker(self):
if self._expirationLoop is not None:
self._expirationLoop.stop()
check_expired_interval = self.check_expired_interval
if check_expired_interval == 0:
self._expirationLoop = None
else:
expirationLoop = LoopingCall(self._clean_expired)
expirationLoop.clock = self.reactor
expirationLoop.start(self.check_expired_interval, now=False)
self._expirationLoop = expirationLoop
示例9: wait_for_status
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def wait_for_status(log,
server_endpoint,
auth_token,
server_id,
expected_status,
interval=5,
clock=None):
"""
Wait until the server specified by server_id's status is expected_status.
@TODO: Timeouts
@TODO: Errback on error statuses.
:param log: A bound logger.
:param str server_endpoint: Server endpoint URI.
:param str auth_token: Keystone Auth token.
:param str server_id: Opaque nova server id.
:param str expected_status: Nova status string.
:param int interval: Polling interval. Default: 5.
:return: Deferred that fires when the expected status has been seen.
"""
log.msg("Checking instance status every {interval} seconds",
interval=interval)
d = Deferred()
def poll():
def _check_status(server):
log.msg("Waiting for status {expected_status} got {status}.",
expected_status=expected_status,
status=server['server']['status'])
if server['server']['status'] == expected_status:
d.callback(server)
sd = server_details(server_endpoint, auth_token, server_id)
sd.addCallback(_check_status)
return sd
lc = LoopingCall(poll)
if clock is not None: # pragma: no cover
lc.clock = clock
def _stop(r):
lc.stop()
return r
d.addCallback(_stop)
return lc.start(interval).addCallback(lambda _: d)
示例10: connectTheEndpoints
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def connectTheEndpoints(endpoints):
doneTrying = []
outstanding = []
errors = []
succeeded = []
actuallyDidIt = Deferred()
def removeMe(result, attempt):
outstanding.remove(attempt)
return result
def connectingDone(result):
if lc.running:
lc.stop()
succeeded.append(True)
for o in outstanding[::]:
o.cancel()
actuallyDidIt.callback(result)
return None
def lastChance():
if doneTrying and not outstanding and not succeeded:
# We've issued our last attempts. There are no remaining
# outstanding attempts; they've all failed. We haven't
# succeeded. Time... to die.
actuallyDidIt.errback(MultiFailure(errors))
def connectingFailed(why):
errors.append(why)
lastChance()
return None
def nextOne():
try:
endpoint = endpoints.next()
except StopIteration:
# Out of endpoints to try! Now it's time to wait for all of
# the outstanding attempts to complete, and, if none of them
# have been successful, then to give up with a relevant
# error. They'll all be dealt with by connectingDone or
# connectingFailed.
doneTrying.append(True)
lc.stop()
lastChance()
else:
attempt = endpoint.connect(factory)
attempt.addBoth(removeMe, attempt)
attempt.addCallbacks(connectingDone, connectingFailed)
outstanding.append(attempt)
lc = LoopingCall(nextOne)
lc.clock = self.reactor
lc.start(0.0)
return actuallyDidIt
示例11: every
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def every(self, interval, f, *args, **kwargs):
"""Call f every interval ticks"""
if not self.__lcs:
self.__lcs = []
tick = kwargs.pop('tick', True)
call = LoopingCall(f, *args, **kwargs)
if tick:
call.clock = self.bot.tick
call.start(interval, False)
self.__lcs.append(call)
return call
示例12: schedule
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def schedule(self, function, interval, report_function):
"""
Schedule C{function} to be called every C{interval} seconds and then
report gathered metrics to C{Graphite} using C{report_function}.
If C{report_function} is C{None}, it just calls the function without
reporting the metrics.
"""
if report_function is not None:
call = self.wrapped(function, report_function)
else:
call = function
task = LoopingCall(call)
if self.clock is not None:
task.clock = self.clock
self.tasks.append((task, interval))
if self.running:
task.start(interval, now=True)
示例13: _test_start_run
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
#.........这里部分代码省略.........
"name": "anonymous",
"permissions": [
{
"uri": "*",
"publish": true,
"subscribe": true,
"call": true,
"register": true
}
]
}
]
}
],
"transports": [
{
"type": "web",
"endpoint": {
"type": "tcp",
"port": 8080
},
"paths": {
"/": {
"directory": ".",
"type": "static"
},
"ws": {
"type": "websocket"
}
}
}
]
},
{
"type": "container",
"options": {
"pythonpath": ["%s"]
},
"components": [
{
"type": "class",
"classname": "test.AppSession",
"realm": "realm1",
"transport": {
"type": "websocket",
"endpoint": {
"type": "tcp",
"host": "127.0.0.1",
"port": 8080
},
"url": "ws://127.0.0.1:8080/ws"
}
}
]
}
]
}
""" % ("/".join(code_location.split(os.sep),)))
with open(code_location + "/test.py", "w") as f:
f.write("""#!/usr/bin/env python
from twisted.internet.defer import inlineCallbacks
from twisted.logger import Logger
from autobahn.twisted.wamp import ApplicationSession
from autobahn.wamp.exception import ApplicationError
class AppSession(ApplicationSession):
log = Logger()
@inlineCallbacks
def onJoin(self, details):
self.log.info("Loaded the component!")
yield self.publish("com.bar", "test")
""")
reactor = SelectReactor()
def _check(lc):
if "Loaded the component!" in self.stdout.getvalue():
if reactor.running:
reactor.stop()
lc.stop()
lc = LoopingCall(_check)
lc.a = (lc,)
lc.clock = reactor
# In case it hard-locks
reactor.callLater(self._subprocess_timeout, reactor.stop)
lc.start(0.1)
cli.run("crossbar",
["start",
"--cbdir={}".format(self.cbdir),
"--logformat=syslogd"],
reactor=reactor)
self.assertIn("Entering reactor event loop", self.stdout.getvalue())
self.assertIn("Loaded the component!", self.stdout.getvalue())
示例14: schedule
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def schedule(self, func, *args, **kw):
task = LoopingCall(CountingProxy(func), *args, **kw)
task.clock = self.clock
task.f.scheduled_event = scheduled = ScheduledEvent(task,
self.clock, self.reactor)
return scheduled
示例15: test_tls_auth_denied
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import clock [as 别名]
def test_tls_auth_denied(self):
"""
A MQTT client offering the wrong certificate won't be authenticated.
"""
reactor, router, server_factory, session_factory = build_mqtt_server()
real_reactor = selectreactor.SelectReactor()
logger = make_logger()
session, pump = connect_application_session(
server_factory, ObservingSession, component_config=ComponentConfig(realm=u"mqtt"))
endpoint = create_listening_endpoint_from_config({
"type": "tcp",
"port": 1099,
"interface": "0.0.0.0",
"tls": {
"certificate": "server.crt",
"key": "server.key",
"dhparam": "dhparam",
"ca_certificates": [
"ca.cert.pem",
"intermediate.cert.pem"
]},
}, FilePath(__file__).sibling('certs').path, real_reactor, logger)
client_endpoint = create_connecting_endpoint_from_config({
"type": "tcp",
"host": "127.0.0.1",
"port": 1099,
"tls": {
# BAD key: trusted by the CA, but wrong ID
"certificate": "client_1.crt",
"hostname": u"localhost",
"key": "client_1.key",
"ca_certificates": [
"ca.cert.pem",
"intermediate.cert.pem"
]},
}, FilePath(__file__).sibling('certs').path, real_reactor, logger)
p = []
l = endpoint.listen(server_factory)
class TestProtocol(Protocol):
data = b""
expected = (
ConnACK(session_present=False, return_code=1).serialise())
def dataReceived(self_, data):
self_.data = self_.data + data
if len(self_.data) == len(self_.expected):
self.assertEqual(self_.data, self_.expected)
real_reactor.stop()
@l.addCallback
def _listening(factory):
d = client_endpoint.connect(Factory.forProtocol(TestProtocol))
@d.addCallback
def _(proto):
p.append(proto)
proto.transport.write(
Connect(client_id=u"test123",
flags=ConnectFlags(clean_session=False)).serialise())
proto.transport.write(
Publish(duplicate=False, qos_level=1, retain=False, topic_name=u"test", payload=b"{}", packet_identifier=1).serialise())
lc = LoopingCall(pump.flush)
lc.clock = real_reactor
lc.start(0.01)
def timeout():
print("Timing out :(")
real_reactor.stop()
print(self.logs.log_text.getvalue())
# Timeout, just in case
real_reactor.callLater(10, timeout)
real_reactor.run()
client_protocol = p[0]
# We get a CONNECT
self.assertEqual(client_protocol.data,
ConnACK(session_present=False, return_code=1).serialise())
client_protocol.data = b""
pump.flush()
# No events!
self.assertEqual(len(session.events), 0)