from threading import Timer
class Interval(object):
"""Interface wrapper for re-occuring functions."""
def __init__(self, f, timeout):
super(Interval, self).__init__()
self.timeout = timeout
self.fn = f
self.next = None
self.done = False
self.setNext()
def setNext(self):
"""Queues up the next call to the intervaled function."""
if not self.done:
self.next = Timer(self.timeout, self.run)
self.next.start()
return self
def run(self):
"""Starts the interval."""
self.fn()
self.setNext()
return self
def stop(self):
"""Stops the interval. Cancels any pending call."""
self.done = True
self.next.cancel()
return self