Sunday, April 1, 2007

how to use the TurboGears scheduler

This is a quick overview of how to use the TG scheduler to, for example, do nightly db cleanups, or similar.

First, put this in your controllers.py:

from turbogears import scheduler
import batch

def startup():
scheduler.add_weekday_task(batch.task, range(1,8), (3,0))

turbogears.startup.call_on_startup.append(startup)

You can see I've put the code I'm going to run in another file, called batch.py, in a function called task(). You can also take a look at scheduler.py in the TG code for more details on the scheduler API, but above I'm basically asking to be called every day at 3 am.

Then, in batch.py:

def task():
hub.threadingLocal = threading_local()
hub.begin()
# do stuff, like clean up your identity database. You can use your ORM objects here.
hub.commit()
hub.end()

Hope this helps!

1 comment:

Unknown said...

Hi, this is very useful, but i think this code is incomplete, where come from hub?