How to launch a function at regular time intervals ?

Christian Heimes lists at cheimes.de
Wed Aug 12 18:01:44 EDT 2009


David wrote:
> Has anyone run into a similar problem (and solved it) ?

Yeah, here is my implementation as a perpetual timer based some cherrypy 
code and threading timer.

import threading

class PerpetualTimer(threading._Timer):
     """A subclass of threading._Timer whose run() method repeats.

     Based on cherrpy.process.plugins.PerpetualTimer
     """
     def __init__(self, interval, function, name=None, daemon=False, 
args=(), kwargs={}):
         super(PerpetualTimer, self).__init__(interval, function, args, 
kwargs)
         self.setName(name)
         self.setDaemon(daemon)

     def run(self):
         while True:
             self.finished.wait(self.interval)
             if self.finished.isSet():
                 return
             self.function(*self.args, **self.kwargs)

     def stop(self, timeout=None):
         self.cancel()
         self.join(timeout)

def callback(egg):
     egg.cook()

timer = PerpetualTimer(100, callback, name="EggTimer", args=(somegg,))
timer.start()

...

timer.stop()

Christian



More information about the Python-list mailing list