Skip to content

Instantly share code, notes, and snippets.

@pope
Created May 1, 2009 00:53
Show Gist options
  • Save pope/104795 to your computer and use it in GitHub Desktop.
Save pope/104795 to your computer and use it in GitHub Desktop.
import time
import bisect
class PeriodicExecutor(object):#{{{
def __init__(self, secs, callable):
self.callable = callable
self.secs = secs
self.next_time_to_run = time.time()
def __call__(self):
self.next_time_to_run = time.time() + self.secs
self.callable()
def __cmp__(self, other):
return cmp(self.next_time_to_run, other.next_time_to_run)
#}}}
class PeriodicReactor(object):#{{{
def __init__(self):
self.executors = []
def add_periodic_executor(self, secs, callable):
# keep the list sorted by time to execute, the earliest time first
bisect.insort(self.executors, PeriodicExecutor(secs, callable))
def __call__(self):
while True and len(self.executors) != 0:
# if the first element isn't ready to execute, then none of them
# are ready
while time.time() >= self.executors[0].next_time_to_run:
executor = self.executors.pop(0)
executor()
# The time to execute has been reset, now add it back in
bisect.insort(self.executors, executor)
time.sleep(self.executors[0].next_time_to_run - time.time())
#}}}
if __name__ == "__main__":
def printA():
print "A"
def printB():
print "B"
r = PeriodicReactor()
r.add_periodic_executor(3, printA)
r.add_periodic_executor(5, printB)
r()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment