There are many ways to run scheduled jobs. More complicated solution can be developed with Celery, Advanced Python Scheduler, python-crontab or with many other solutions. But if you are looking for a quick and simple way to run scheduled jobs, then cron is the right tool (if you are using Windows, then services are similar alternative).
Running a simple python script using cron is simple. First we need to edit crontab
1 |
$ crontab -e |
Every line defined one cron task. Every task has to have correct syntax
1 |
0 */2 * * * /usr/bin/python /home/erol/script.py |
and our script.py
1 2 3 |
# script.py print "it works" |
We will not go into details. If you want to read more about it, there are many articles. When we save, we are notified (if we correctly defined everything) that task has been installed. In our case, it will run our script.py every 2 hours.
Mixing it with Django
Running cron with Django can be a little bit more complicated. The reason lays in fact that Django needs settings to be included to run correctly. This can sometimes be pain in the ass because of the paths.
Easy way to solve this is to use Knosos.
Kronos makes it really easy to schedule tasks with cron.
With Knosos we need to register tasks.
1 2 3 4 5 6 7 8 |
# app/cron.py import kronos import random @kronos.register('0 */2 * * *') def talk(): print "it works" |
What will this do? It will register a task and run is every 2 hours. It will automatically include everything and define correct path, so we can also use our app code; for example models.
1 2 3 4 5 6 7 8 9 10 |
# app/cron.py import kronos import random from models import User @kronos.register('0 */2 * * *') def talk(): word = User.objects.next_word() # custom query to each time load next word print word |
To test everything, we run
1 2 |
$ python manage.py runtask talk it works |
and to register it
1 2 |
$ python manage.py installtasks Installed 1 task. |
If we check crontab, we will see something similar to
1 2 |
$ crontab -l 0 */2 * * * /usr/bin/python /home/erol/app/manage.py runtask talk --settings=app.settings |
If we did everything correctly, it should work and run our talk method every 2 hours.
Extra advice
While running tasks on my Linux machine, I was always getting email from Cron Deamon. This can be annoying, so we can simply “disable” it. Actually, we can redirect cron output to /dev/null. Just add setting KRONOS_POSTFIX.
1 |
KRONOS_POSTFIX = "&> /dev/null" |