本文整理汇总了Python中twisted.internet.task.LoopingCall.start方法的典型用法代码示例。如果您正苦于以下问题:Python LoopingCall.start方法的具体用法?Python LoopingCall.start怎么用?Python LoopingCall.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.task.LoopingCall
的用法示例。
在下文中一共展示了LoopingCall.start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_reactor
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
def build_reactor(options, **kwargs):
web_socket_instance = FilteredWebSocketFactory(**kwargs)
subscriber = kwargs.pop("subscriber", None)
if options.key and options.cert:
with open(options.key) as keyFile:
with open(options.cert) as certFile:
cert = ssl.PrivateCertificate.loadPEM(keyFile.read() + certFile.read())
reactor.listenSSL(options.port, web_socket_instance, cert.options())
else:
reactor.listenTCP(
options.port,
web_socket_instance
)
if subscriber is not None:
reactor.callInThread(
subscriber.listener,
web_socket_instance
)
reactor.addSystemEventTrigger(
"before",
"shutdown",
subscriber.kill
)
# Start the consumer loop
consumer_loop = LoopingCall(
web_socket_instance.consumer
)
consumer_loop.start(0.001, now=False)
return web_socket_instance
示例2: LeaseService
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
class LeaseService(Service):
"""
Manage leases.
In particular, clear out expired leases once a second.
:ivar _reactor: A ``IReactorTime`` provider.
:ivar _persistence_service: The persistence service to act with.
:ivar _lc: A ``twisted.internet.task.LoopingCall`` run every second
to update the configured leases by releasing leases that have
expired.
"""
def __init__(self, reactor, persistence_service):
self._reactor = reactor
self._persistence_service = persistence_service
def startService(self):
self._lc = LoopingCall(self._expire)
self._lc.clock = self._reactor
self._lc.start(1)
def stopService(self):
self._lc.stop()
def _expire(self):
now = datetime.fromtimestamp(self._reactor.seconds(), tz=UTC)
def expire(leases):
updated_leases = leases.expire(now)
for dataset_id in set(leases) - set(updated_leases):
_LOG_EXPIRE(dataset_id=dataset_id,
node_id=leases[dataset_id].node_id).write()
return updated_leases
return update_leases(expire, self._persistence_service)
示例3: PollingDataStream
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
class PollingDataStream(DataStream):
""" A self-polling data stream.
This class represents a data stream that wakes up at a given frequency,
and calls the :meth:`poll` method.
"""
frequency = None # Either a timedelta object, or the number of seconds
now = False
def __init__(self):
super(PollingDataStream, self).__init__()
self.timer = LoopingCall(self.poll)
if isinstance(self.frequency, timedelta):
seconds = (
self.frequency.seconds
+ (self.frequency.days * 24 * 60 * 60)
+ (self.frequency.microseconds / 1000000.0)
)
else:
seconds = self.frequency
log.debug("Setting a %s second timer" % seconds)
self.timer.start(seconds, now=self.now)
def poll(self):
raise NotImplementedError
def stop(self):
super(PollingDataStream, self).stop()
try:
if hasattr(self, "timer"):
self.timer.stop()
except Exception, e:
self.log.warn(e)
示例4: _ExchangeRate
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
class _ExchangeRate(object):
"""Download an exchange rate from Yahoo Finance using Twisted."""
def __init__(self, name):
self._value = None
self._name = name
# External API:
def latest_value(self):
"""Return the latest exchange rate value.
May be None if no value is available.
"""
return self._value
def start(self):
"""Start the background process."""
self._lc = LoopingCall(self._download)
# Run immediately, and then every 30 seconds:
self._lc.start(30, now=True)
def _download(self):
"""Download the page."""
print("Downloading!")
def parse(result):
print("Got %r back from Yahoo." % (result,))
values = result.strip().split(",")
self._value = float(values[1])
d = getPage(
"http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=%s=X"
% (self._name,))
d.addCallback(parse)
d.addErrback(log.err)
return d
示例5: openShell
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
def openShell(self, transport):
"""
Write 60 lines of data to the transport, then exit.
"""
proto = protocol.Protocol()
proto.makeConnection(transport)
transport.makeConnection(wrapProtocol(proto))
# Send enough bytes to the connection so that a rekey is triggered in
# the client.
def write(counter):
i = counter()
if i == 60:
call.stop()
transport.session.conn.sendRequest(
transport.session, 'exit-status', '\x00\x00\x00\x00')
transport.loseConnection()
else:
transport.write("line #%02d\n" % (i,))
# The timing for this loop is an educated guess (and/or the result of
# experimentation) to exercise the case where a packet is generated
# mid-rekey. Since the other side of the connection is (so far) the
# OpenSSH command line client, there's no easy way to determine when the
# rekey has been initiated. If there were, then generating a packet
# immediately at that time would be a better way to test the
# functionality being tested here.
call = LoopingCall(write, count().next)
call.start(0.01)
示例6: ProvisionerQueryService
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
class ProvisionerQueryService(ServiceProcess):
"""Provisioner querying service
"""
declare = ServiceProcess.service_declare(name='provisioner_query',
version='0.1.0',
dependencies=[])
def slc_init(self):
interval = float(self.spawn_args.get("interval_seconds",
DEFAULT_QUERY_INTERVAL))
self.client = ProvisionerClient(self)
log.debug('Starting provisioner query loop - %s second interval',
interval)
self.loop = LoopingCall(self.query)
self.loop.start(interval)
def slc_terminate(self):
if self.loop:
self.loop.stop()
@defer.inlineCallbacks
def query(self):
try:
yield self._do_query()
except Exception,e:
log.error("Error sending provisioner query request: %s", e,
exc_info=True)
示例7: make_lc
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [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
示例8: UdpSender
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
class UdpSender(DatagramProtocol):
"""
Class that will send UDP packets to UDP Listener
"""
def __init__(self, host, count, size, duration):
# LoopingCall does not know whether UDP socket is actually writable
self.looper = None
self.host = host
self.count = count
self.duration = duration
self.start = time.time()
self.sent = 0
self.data = array.array('c', 'X' * size)
def startProtocol(self):
self.looper = LoopingCall(self.sendData)
period = self.duration / float(self.count)
self.looper.start(period, now=False)
def stopProtocol(self):
if (self.looper is not None):
self.looper.stop()
self.looper = None
def datagramReceived(self, data, (host, port)):
pass
示例9: Blinker
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
class Blinker(object):
def __init__(self, port, interval=0.5):
self.port = port
self.interval = interval
self.state = None
self.transition = None
def set(self, *args, **kwargs):
self.blink()
def unset(self):
self.transition_stop()
self.port.unset()
def blink(self):
self.transition_stop()
self.transition = LoopingCall(self.blink_task)
self.transition.start(self.interval)
def transition_stop(self):
if self.transition and self.transition.running:
self.transition.stop()
def blink_task(self):
if self.state:
self.state = False
self.port.set()
else:
self.state = True
self.port.unset()
示例10: begin_logging
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
def begin_logging(self):
def logging_callback(*args, **kwargs):
print("number of players: " + str(len(self.clients)))
print("number of lobbies: " + str(len(self.lobbys)))
print("Total number of connects: " + str(self.total_clients))
looping_call = LoopingCall(logging_callback)
looping_call.start(60.0*60.0) #every hour
示例11: authenticate
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
def authenticate(self, twistedStanza):
"""authentication callback"""
self._send = twistedStanza.send
# add observers for incoming message / presence requests
# twistedStanza.addObserver('/iq', self.iqHandler)
# twistedStanza.addObserver('/presence', self.dialogHandler.presenceHandler)
twistedStanza.addObserver("/presence", self.presenceHandler)
twistedStanza.addObserver("//event/stream/error", self.streamErrorHandler)
# twistedStanza.addObserver('//event/stream/error', self.streamErrorHandler)
# twistedStanza.addObserver('/message', self.dialogHandler.messageHandler)
twistedStanza.addObserver("/message", self.messageHandler)
self.requestRoster()
# let'em know we are online
presence = domish.Element((JABBER_CLIENT_NS, "presence"))
presence.addElement("status").addContent("Online")
self.send(presence)
keepalive = LoopingCall(self.loopEntry)
keepalive.start(60)
self.joinChatrooms(self.chatrooms)
示例12: LiveStream
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
class LiveStream(WebSocketClientProtocol): # pragma: no cover
""" Internal class used to call the websocket callbacks. """
sendqueue = []
sending = False
def _sender(self):
if len(self.sendqueue):
while self.sendqueue:
data = self.sendqueue.pop()
self.sendMessage(data)
def queueMessage(self, message):
self.sendqueue.append(message)
if not self.sending:
self.sending = True
self._loopingcall = LoopingCall(self._sender)
self._loopingcall.start(0.1)
def onOpen(self):
self.factory.datasift['send_message'] = self.queueMessage
self.factory.datasift['on_open']()
def onClose(self, wasClean, code, reason):
self.factory.datasift['on_close'](wasClean, code, reason)
def onMessage(self, msg, binary):
self.factory.datasift['on_message'](msg, binary)
self.factory.resetDelay()
def onPing(self, payload):
self.factory.resetDelay()
示例13: addSlave
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
def addSlave(self, slaveSpec):
# try to catch a slave reconnection; else assign a new slave ID
try:
(connectedSlave, connectedSlaveStatus, connectedSlaveTask) = self._getSlaveBySlaveSpec(slaveSpec, asTuple=True)
slaveId = self._getSlaveIdByObject(connectedSlave)
log.warn("Slave %d (%s://%s:%d/%s) reconnecting. Resetting slave state!" % (slaveId, connectedSlave.slaveSpec.scheme, connectedSlave.slaveSpec.host, connectedSlave.slaveSpec.port, connectedSlave.slaveSpec.path))
except SlaveNotFound:
slaveNo = self._getSlaveNo()
else:
slaveNo = slaveId
slave = SlavePerspective(slaveSpec)
status = SlaveState()
status.state = SlaveState.CONNECTED
# check that the slave is up and running
request = self.checkHealth(slave)
yield request
if request.result != True:
raise SlaveConnectionError
else:
status.state = SlaveState.IDLE
# set up a heartbeat call
task = LoopingCall(self.checkHealth, slave)
task.start(60, now=False)
self.slaves[slaveNo] = (slave, status, task)
returnValue(slaveNo)
示例14: NetworkSpeedDaemon
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
class NetworkSpeedDaemon(VMCDaemon):
"""
I enque fake SIG_SPEED UnsolicitedNotifications
"""
def __init__(self, frequency, device, notification_manager):
super(NetworkSpeedDaemon, self).__init__(frequency, device, notification_manager)
self.netspeed = NetworkSpeed()
def start(self):
log.msg("DAEMONS: DAEMON %s started..." % self.__class__.__name__)
self.netspeed.start()
self.loop = LoopingCall(self.function)
self.loop.start(self.frequency)
def stop(self):
log.msg("DAEMONS: DAEMON %s stopped..." % self.__class__.__name__)
self.loop.stop()
self.netspeed.stop()
def function(self):
up, down = self.netspeed["up"], self.netspeed["down"]
n = N.UnsolicitedNotification(N.SIG_SPEED, bps_to_human(up, down))
self.manager.on_notification_received(n)
示例15: EventGenerator
# 需要导入模块: from twisted.internet.task import LoopingCall [as 别名]
# 或者: from twisted.internet.task.LoopingCall import start [as 别名]
class EventGenerator(Node):
""" (TEST) A timer-based event generator """
# --- Initialization
def __init__(self):
self.count = 0
# --- Interfaces
def configure(self):
self.events = (
'event1',
'event2',
)
def setup(self):
self.status.set_GREEN()
self.loop1 = LoopingCall(self.loop_cb1)
self.loop1.start(3, False)
self.loop2 = LoopingCall(self.loop_cb2)
self.loop2.start(4, False)
# --- Workers
def loop_cb1(self):
self.count += 1
self.sendEvent('event1', self.count)
def loop_cb2(self):
self.count += 1
self.sendEvent('event2', self.count)