Scheduling Tasks with TurboGears

TurboGears includes a scheduler that is based on Kronos by Irmen de Jong. This scheduler makes it easy to have recurring tasks run as needed.

To use the scheduler, set the "tg.scheduler" config variable to True in your [global] configuration. This tells TurboGears to start the scheduler when the server starts.

Scheduling Jobs

There are three functions you can use to schedule jobs. All three functions return a "Task" object. If you hold on to that Task object, you can later cancel it by calling turbogears.scheduler.cancel with that Task.

All three scheduling functions take:

action
The callable that will be called at the time you request
args
Tuple of positional parameters to pass to the action
kw
Keyword arguments to pass to the action
processmethod
By default, each task will be run in a new thread. You can also pass in turbogears.scheduler.method.sequential or turbogears.scheduler.method.forked. Sequential means that the task will run in the same thread as the scheduler, and should only be used for quick tasks. Forked means to fork a new process to run the job, which is sometimes more effective for intense jobs, particularly on multiprocessor machines (due to Python's architecture).
taskname
Tasks can have a name (stored in task.name), which can help if you're trying to keep track of many tasks.

In addition to these common parameters, the three scheduling functions each offer additional options to determine when they run. Here are the three functions and their parameters for how often to run:

add_interval_task
Pass in initialdelay with a number of seconds to wait before running and an interval with the number of seconds between runs. For example, an initialdelay of 600 and interval of 60 would mean "start running after 10 minutes and run every 1 minute after that".
add_weekday_task
Runs on certain days of the week. Pass in a list or tuple of weekdays from 1-7 (where 1 is Monday). Additionally, you need to pass in timeonday which is the time of day to run. timeonday should be a tuple with (hour, minute).
add_monthday_task
Runs on certain days of the month. Pass in a list or tuple of monthdays from 1-31, and also pass in timeonday which is an (hour, minute) tuple of the time of day to run the task.