Skip to content

Instantly share code, notes, and snippets.

@joepie91
Created January 24, 2014 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joepie91/8597001 to your computer and use it in GitHub Desktop.
Save joepie91/8597001 to your computer and use it in GitHub Desktop.
ZeroMQ Timer (for poller loop)
#!/usr/bin/env python2
import zmq, zmqtimer, sys, socket
ctx = zmq.Context()
poller = zmq.Poller()
def sample():
print "I am a sample function that runs every five and a half seconds!"
timers = zmqtimer.ZmqTimerManager()
timers.add_timer(zmqtimer.ZmqTimer(5.5, sample))
grabber = ctx.socket(zmq.SUB)
grabber.setsockopt(zmq.SUBSCRIBE, "")
grabber.connect("ipc:///tmp/recv_socket")
poller.register(grabber, zmq.POLLIN)
while True:
timers.check()
socks = dict(poller.poll(timers.get_next_interval()))
for sock in socks:
if socks[sock] == zmq.POLLIN:
data = sock.recv()
print "Received: %s" % data
import time
class ZmqTimerManager(object):
def __init__(self):
self.timers = []
self.next_call = 0
def add_timer(self, timer):
self.timers.append(timer)
def check(self):
if time.time() > self.next_call:
for timer in self.timers:
timer.check()
def get_next_interval(self):
if time.time() >= self.next_call:
call_times = []
for timer in self.timers:
call_times.append(timer.get_next_call())
self.next_call = min(call_times)
if self.next_call < time.time():
return 0
else:
return (self.next_call - time.time()) * 1000
else:
return (self.next_call - time.time()) * 1000
class ZmqTimer(object):
def __init__(self, interval, callback):
self.interval = interval
self.callback = callback
self.last_call = 0
def check(self):
if time.time() > (self.interval + self.last_call):
self.callback()
self.last_call = time.time()
def get_next_call(self):
return self.last_call + self.interval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment