Advertisement
Guest User

Untitled

a guest
Jul 1st, 2016
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. import uuid
  2. import time
  3. import random
  4. import zmq
  5.  
  6.  
  7. class Worker(object):
  8.     def __init__(self, stop_event):
  9.         self.stop_event = stop_event
  10.         self.context = zmq.Context()
  11.         self.socket = self.context.socket(zmq.DEALER)
  12.         # We don't need to store the id anymore, the socket will handle it
  13.         # all for us.
  14.         self.socket.identity = uuid.uuid4().hex[:4].encode('utf8')
  15.         self.socket.connect('tcp://127.0.0.1:5755')
  16.  
  17.     def run(self):
  18.         try:
  19.             # Send a connect message
  20.             self.socket.send_json({'message': 'connect'})
  21.             # Poll the socket for incoming messages. This will wait up to
  22.             # 0.1 seconds before returning False. The other way to do this
  23.             # is is to use zmq.NOBLOCK when reading from the socket,
  24.             # catching zmq.AGAIN and sleeping for 0.1.
  25.             while not self.stop_event.is_set():
  26.                 if self.socket.poll(100):
  27.                     # Note that we can still use send_json()/recv_json() here,
  28.                     # the DEALER socket ensures we don't have to deal with
  29.                     # client ids at all.
  30.                     job_id, work = self.socket.recv_json()
  31.                     self.socket.send_json(
  32.                         {'message': 'job_done',
  33.                          'result': self._do_work(work),
  34.                          'job_id': job_id})
  35.         except KeyboardInterrupt:
  36.             pass
  37.         finally:
  38.             self._disconnect()
  39.  
  40.     def _disconnect(self):
  41.         """Send the Controller a disconnect message and end the run loop.
  42.        """
  43.         self.stop_event.set()
  44.         self.socket.send_json({'message': 'disconnect'})
  45.  
  46.     def _do_work(self, work):
  47.         result = work['number'] ** 2
  48. #         time.sleep(random.randint(1, 10))
  49.         return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement