本文整理匯總了Python中zmq.eventloop.ioloop.DelayedCallback.stop方法的典型用法代碼示例。如果您正苦於以下問題:Python DelayedCallback.stop方法的具體用法?Python DelayedCallback.stop怎麽用?Python DelayedCallback.stop使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類zmq.eventloop.ioloop.DelayedCallback
的用法示例。
在下文中一共展示了DelayedCallback.stop方法的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: MqAsyncReq
# 需要導入模塊: from zmq.eventloop.ioloop import DelayedCallback [as 別名]
# 或者: from zmq.eventloop.ioloop.DelayedCallback import stop [as 別名]
#.........這裏部分代碼省略.........
port = Parameter.objects.get(key='mq-req_rep_port')
self.endpoint = "tcp://{0}:{1}".format(ip.value, port.value)
socket = ZmqSocket(context, zmq.REQ)
ioloop = IOLoop.instance()
self.service = service
self.stream = ZMQStream(socket, ioloop)
self.stream.on_recv(self._on_message)
self.can_send = True
self._proto_prefix = [ PROTO_VERSION, service]
self._tmo = None
self.timed_out = False
socket.connect(self.endpoint)
return
def shutdown(self):
"""Method to deactivate the client connection completely.
Will delete the stream and the underlying socket.
.. warning:: The instance MUST not be used after :func:`shutdown` has been called.
:rtype: None
"""
if not self.stream:
return
self.stream.socket.setsockopt(zmq.LINGER, 0)
self.stream.socket.close()
self.stream.close()
self.stream = None
return
def request(self, msg, timeout=None):
"""Send the given message.
:param msg: message parts to send.
:type msg: list of str
:param timeout: time to wait in milliseconds.
:type timeout: int
:rtype None:
"""
if not self.can_send:
raise InvalidStateError()
if type(msg) in (bytes, str):
msg = [msg]
# prepare full message
to_send = self._proto_prefix[:]
to_send.extend(msg)
self.stream.send_multipart(to_send)
self.can_send = False
if timeout:
self._start_timeout(timeout)
return
def _on_timeout(self):
"""Helper called after timeout.
"""
self.timed_out = True
self._tmo = None
self.on_timeout()
return
def _start_timeout(self, timeout):
"""Helper for starting the timeout.
:param timeout: the time to wait in milliseconds.
:type timeout: int
"""
self._tmo = DelayedCallback(self._on_timeout, timeout)
self._tmo.start()
return
def _on_message(self, msg):
"""Helper method called on message receive.
:param msg: list of message parts.
:type msg: list of str
"""
if self._tmo:
# disable timout
self._tmo.stop()
self._tmo = None
# setting state before invoking on_message, so we can request from there
self.can_send = True
self.on_message(msg)
return
def on_message(self, msg):
"""Public method called when a message arrived.
.. note:: Does nothing. Should be overloaded!
"""
pass
def on_timeout(self):
"""Public method called when a timeout occured.
.. note:: Does nothing. Should be overloaded!
"""
pass
示例2: Client
# 需要導入模塊: from zmq.eventloop.ioloop import DelayedCallback [as 別名]
# 或者: from zmq.eventloop.ioloop.DelayedCallback import stop [as 別名]
#.........這裏部分代碼省略.........
return self.request(data, timeout)
def _on_message(self, message):
"""Helper method called on message receive.
:param message: list of message parts.
:type message: list of str
"""
message.pop(0) # remove empty string
protocol_version = message.pop(0)
if protocol_version != MDP_WORKER_VERSION: # version check, ignore old versions
return
message_type = message.pop(0)
if message_type == b'\x02': # partial message
worker = message.pop(0)
try:
msg = msgpack.unpackb(message[0])
except:
msg = message[0]
self.on_partial_message(worker, msg)
elif message_type == b'\x03': # final message
worker = message.pop(0)
try:
msg = msgpack.unpackb(message[0])
except:
msg = message[0]
self.on_message(worker, msg)
if message[0] not in self.multicast_already_received:
self.multicast_already_received.append(worker)
if self.multicast_services is None or len(self.multicast_already_received) == len(self.multicast_services):
self.stop_waiting()
elif message_type == b'\x04': # error message
worker = message.pop(0)
self.on_error_message(worker, message[0])
self.stop_waiting()
elif message_type == b'\x05': # multicast start, load list of multicast services
self.multicast_services = message
self.multicast_already_received = []
self.on_multicast_start(message)
elif message_type == b'\x06': # exception message
worker = message.pop(0)
try:
msg = msgpack.unpackb(message[0])
except:
msg = {b'class': 'Exception', b'message': 'parsing failed', b'traceback': message[0]}
self.on_exception_message(worker, msg[b'class'], msg[b'message'], msg[b'traceback'])
if message[0] not in self.multicast_already_received:
self.multicast_already_received.append(worker)
if self.multicast_services is None or len(self.multicast_already_received) == len(self.multicast_services):
self.stop_waiting()
#else: unknown type - do nothing
return
def wait_for_reply(self):
"""Start waiting for replies
"""
self.ioloop.start()
def stop_waiting(self):
"""Stop waiting for replies and cancel timeout
"""
self.ioloop.stop()
示例3: MDPWorker
# 需要導入模塊: from zmq.eventloop.ioloop import DelayedCallback [as 別名]
# 或者: from zmq.eventloop.ioloop.DelayedCallback import stop [as 別名]
class MDPWorker(ZMQStream):
def __init__(self, broker, service, io_loop=None):
"""Create and setup an MDP worker.
@param broker A string containing the broker's URL
@param service A string containing the service name
@param io_loop An existing I/O loop object. If None, the default will be used.
"""
self.service=service
self._broker = broker
self.ctx = zmq.Context()
sock = self.ctx.socket(zmq.DEALER)
ZMQStream.__init__(self, sock, io_loop)
# last watchdog timer tick
self.watchdog = 0
# connection callback one-shot
self._conncb = DelayedCallback(self.send_ready, 3000, self.io_loop)
# heartbeat callback..runs continuous when connected
self._hbcb = PeriodicCallback(self.send_heartbeat, 2000, self.io_loop)
# number of connection attempts
self._conn_attempt = 0
# waiting to connect state
self._waiting_to_connect = True
# have we been disconnected? (flags a reconnect attempt)
self.disconnected = False
# connect the socket and send a READY when the io_loop starts
self.connect(self._broker)
self._conncb.start()
def reset_watchdog(self):
"""Private method used to reset the HEARTBEAT watchdog
"""
self.watchdog = time.time()
def disconnect(self):
"""Disconnect from the broker.
"""
logging.info("Disconnected from broker")
self.on_recv(None) # stop message processing
self._conncb.stop() # stop any pending reconnect
self._hbcb.stop() # stop heartbeats
self.disconnected = True
self.io_loop.stop() # stop the I/O loop. If it's used by something else, the caller can restart it
def reconnect(self):
"""Try to reconnect to the broker.
"""
if self.disconnected: # don't try and reconnect, we got an explicit disconnect
return
logging.info("Attempting to reconnect to broker")
self._hbcb.stop()
self._conn_attempt = 0
self._waiting_to_connect = True
try:
self.connect(self._broker)
except ZMQError:
logging.exception()
self.io_loop.stop()
return
self._conncb.start()
def send_ready(self):
"""Send a READY message.
"""
if not self._waiting_to_connect:
# connected already
return
if self.disconnected: # don't try and connect, we got an explicit disconnect
return
logging.debug("Sending READY")
if self._conn_attempt >= 10:
logging.error("10 connection attempts have failed. Giving up.")
return
self._conn_attempt += 1
logging.debug("Connection attempt %i" % self._conn_attempt)
rdy = [b'', MDPW_VER, b'\x01', self.service]
self.on_recv(self.on_message)
self.send_multipart(rdy)
# There is no reply to READY so
# we must assume we are connected unless we see a DISCONNECT
self._waiting_to_connect = False
self._disconed = False
self.reset_watchdog()
self._hbcb.start()
def send_reply(self, client, msg, partial=False):
"""Send a reply to a client. This is typically called from on_request()
@param client The client identifier as passed to on_request()
@param msg The message to send to the client. If this is a list, it's appended to the multipart;
otherwise it is converted to a string and sent as a single frame.
@param partial If this is True, the message is sent as a PARTIAL and at least one
more call must be made to send_reply(). Otherwise a FINAL is sent and
not more calls should be made to send_reply() until another request is processed.
"""
self._hbcb.stop() # stop while sending other messages
if partial:
rply = [b'', MDPW_VER, b'\x03', client, b'']
else:
#.........這裏部分代碼省略.........
示例4: DeviceConnection
# 需要導入模塊: from zmq.eventloop.ioloop import DelayedCallback [as 別名]
# 或者: from zmq.eventloop.ioloop.DelayedCallback import stop [as 別名]
class DeviceConnection(object):
SERVICE_NAME = 'device' # service to connect to
TIMEOUT = 5 # time to wait for answer in seconds
# Number of connections to try before restarting when in incorrect state
CONNECTION_ATTEMPS = 3
HB_INTERVAL = 1000 * 10 # in milliseconds
def __init__(self, context, device_id, address):
self.context = context
self.device_id = device_id
self.address = address
self.ticker = None
self.updater = None
self.socket = None
self.can_send = False
self._restart()
self.heartbeat()
return
def _restart(self):
self.shutdown()
self.socket = self.context.socket(zmq.REQ)
self.socket.setsockopt(zmq.LINGER, 0)
self.socket.connect(self.address)
self.can_send = True
self.connection_attempts = 0
self.device_state = 'unknown'
self.ticker = PeriodicCallback(self.heartbeat,
DeviceConnection.HB_INTERVAL)
self.ticker.start()
# delay = seconds_till_next('hour', duration=1) + 2 # 2 second buffer
delay = 60 # send update one minute after startup
self.updater = DelayedCallback(self.update, delay * 1000)
self.updater.start()
return
def shutdown(self):
if self.ticker:
self.ticker.stop()
self.ticker = None
if self.updater:
self.updater.stop()
if self.socket:
self.socket.close()
self.socket = None
self.can_send = False
return
def send(self, message):
if not self.can_send:
self.connection_attempts += 1
logger.error("DeviceConnection is not in state to send")
return None
else:
self.connection_attempts = 0
self.can_send = False
logger.debug("DeviceConnection sending {0}".format(message))
reply = mdp_request(self.socket,
DeviceConnection.SERVICE_NAME,
message,
DeviceConnection.TIMEOUT)
if reply:
logger.debug("DeviceConnection reply received: {0}".format(reply))
self.can_send = True
return reply
else:
# Timeout! Will be restarted at next heartbeat
logger.warn("DeviceConnection timeout. Will be restarted at next heartbeat")
self.connection_attempts = DeviceConnection.CONNECTION_ATTEMPS
return None
def heartbeat(self):
if self.connection_attempts >= DeviceConnection.CONNECTION_ATTEMPS:
logger.warn("DeviceConnection attempts max reached. Restarting connection.")
self._restart()
message = HeartbeatMessage(self.device_id)
reply = self.send([pickle.dumps(message)])
if reply:
#.........這裏部分代碼省略.........
示例5: GrainBinService
# 需要導入模塊: from zmq.eventloop.ioloop import DelayedCallback [as 別名]
# 或者: from zmq.eventloop.ioloop.DelayedCallback import stop [as 別名]
class GrainBinService(object):
SERVICE_NAME = 'grain_bin'
def __init__(self, context, device_id, address):
self.context = context
self.address = address
self.device_id = device_id
self.socket = None
# delay = seconds_till_next('hour', duration=1) + 10 # 10 second buffer
delay = 120 # 2 minutes after startup
self.updater = DelayedCallback(self.update, delay * 1000)
self.updater.start()
return
def shutdown(self):
self.updater.stop()
return
def update(self):
self.updater.stop()
if internal_dealer.check_connection():
logger.info("Sending update for all grainbins")
socket = self.context.socket(zmq.REQ)
socket.setsockopt(zmq.LINGER, 0)
socket.connect(self.address)
update = GrainbinUpdate(self.device_id, 'farm_monitor')
update.create()
message = [pickle.dumps(update)]
reply = mdp_request(socket, 'grainbin', message, 5)
if reply:
message = pickle.loads(reply[1])
logger.debug("reply from farm monitor for update: {0}".format(message.reply))
# delay = seconds_till_next('hour', duration=1) + 10 # 10 second buffer
delay = 60 * 60 # send next update in one hour
self.updater = DelayedCallback(self.update, delay * 1000)
self.updater.start()
return
def update_individual(self, bus_number):
if internal_dealer.check_connection():
logger.info("Sending update for grainbin: {0}".format(bus_number))
socket = self.context.socket(zmq.REQ)
socket.setsockopt(zmq.LINGER, 0)
socket.connect(self.address)
update = GrainbinUpdate(self.device_id, 'farm_monitor')
update.create(bus_number=bus_number)
message = [pickle.dumps(update)]
reply = mdp_request(socket, 'grainbin', message, 5)
if reply:
message = pickle.loads(reply[1])
logger.debug("reply from farm monitor for update: {0}".format(message.reply))
return
def rescan(self, bus_number):
logger.info("sending rescan for grainbin: {0}".format(bus_number))
info = GrainbinInfo(self.device_id, 'farm_monitor')
info.create()
message = [pickle.dumps(info)]
socket = self.context.socket(zmq.REQ)
socket.setsockopt(zmq.LINGER, 0)
socket.connect(self.address)
reply = mdp_request(socket, 'grainbin', message, 5)
if reply:
message = pickle.loads(reply[1])
logger.debug("reply from farm monitor for rescan: {0}".format(message.reply))
return