Running cron tasks with Django and Kronos

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

Every line defined one cron task. Every task has to have correct syntax

and our script.py

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.

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.

To test everything, we run

and to register it

If we check crontab, we will see something similar to

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.