Tag Archives: unix

Django cronjobs

In web applications sometimes you want to run processes that are seperated from the Request/Response cycle, like scheduled jobs that run at a specific time of a day. Scheduling such jobs in a unix environment is very easy with cronjobs. You just need to edit the crontab file and define a time and a command(a script to be run in this case) to execute at that time.

This post is about how to schedule such Django programs, that is python programs that import and use the Django framework.

This should be trivial because a Django program is another python program. But there is an important step to be done in about for Django modules to be discovered and run. That is to specify the Django settings file.

Let’s say there is a Django project called mysite and a Django app called myapp that has a method called runJob() in a python module called jobs.py that needs to be called every 30 mins.

let’s write a python script called thescript.py that will run every 30 minutes as a cronjob that will in turn call the runjob method.

thescript.py
#######################################

import os

os.environ[‘DJANGO_SETTINGS_MODULE’] = ‘settings’

from myapp.jobs import runJob

runJob()

###################################

For easiness save the ‘thescript.py’ in the mysite folder.

Then open a console and enter crontab -e to edit your cron file. Enter the following line.

*/30 * * * * python /path to mysite/thescript.py > logfile 2>&1

This will run the ‘thescript.py’ file every 30 minutes and any output would be directed to the logfile specified and the last ‘2>&1’ tells that no email should be sent to the administrator. For more information on how to write the crontab file have a look at this.

That is how easy it is to schedule a Django cronjob in an Unix environment.

Advertisements