Created
January 24, 2014 13:15
-
-
Save joepie91/8597001 to your computer and use it in GitHub Desktop.
ZeroMQ Timer (for poller loop)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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