Check out the sched module in Python's standard library -- per se, it doesn't directly support periodic timers, only one-off "events", but the standard trick to turn a one-off event into a periodic timer applies (the callable handling the one-off event just reschedules itself for the next repetition, before moving on to doing real work).
It may be handy to define a "scheduled periodic timer" class to encapsulate the key ideas:
class spt(object):
def __init__(self, scheduler, period):
self._sched = scheduler
self._period = period
self._event = None
def start(self):
self._event = self._sched.enter(0, 0, self._action, ())
def _action(self):
self._event - self._sched.enter(self._period, 0, self._action, ())
self.act()
def act(self):
print "hi there"
def cancel(self):
self._sched.cancel(self._event)
To associate a meaningful action to a scheduled periodic timer, subclass spt and override the act
method (a Template Method design pattern). You can of course choose more flexible architectures, such as having __init__
take a callable and arguments as well as a scheduler (an instance of self.scheduler
) and a period (as a float in seconds, if you instantiate the scheduler in the standard way with time.time and time.sleep); optionally you might also want to set a priority there (maybe with a default value of 0) rather than using the constant 0 priority I'm using above.