Wednesday, June 22, 2011

cron-like functionality (sched module)

The Python standard library includes a handy little scheduler, with which you can do cron-like functionality.  The following code will print the current time every 5 seconds forever.

>>> import sched
>>> import datetime
>>> import time
>>> s = sched.scheduler(time.time, time.sleep)
>>> def print_time():
...    print datetime.datetime.now()
...    s.enter(5, 1, print_time, ())
...
>>> print_time()
2011-06-22 17:56:41.262000
>>> s.run()
2011-06-22 17:56:46.668000
2011-06-22 17:56:51.669000
2011-06-22 17:56:56.669000
2011-06-22 17:57:01.669000

This is a simple example of continuation passing style -- where functions "schedule" each other to run at a later time rather than calling directly.

No comments:

Post a Comment