How do I get a Cron like scheduler in Python?

jamesh picture jamesh · Dec 17, 2008 · Viewed 295.1k times · Source

I'm looking for a library in Python which will provide at and cron like functionality.

I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.

For those unfamiliar with cron: you can schedule tasks based upon an expression like:

 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday
 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays.

The cron time expression syntax is less important, but I would like to have something with this sort of flexibility.

If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.

Edit I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.

To this end, I'm looking for the expressivity of the cron time expression, but in Python.

Cron has been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.

Answer

dbader picture dbader · May 28, 2013

If you're looking for something lightweight checkout schedule:

import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)

while 1:
    schedule.run_pending()
    time.sleep(1)

Disclosure: I'm the author of that library.