Last Updated: February 25, 2016
·
21.16K
· emi420

Run Django commands using cron

You can run custom django-admin commands adding a management/commands directory to the Django application and a file with the command's code, for example:

(management/commands/exporter.py)

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    args = ''
    help = 'Export data to remote server'

    def handle(self, *args, **options):
        # do something here

And then, in the command line:

$ python manage.py exporter

Now, it's easy to add a new cron task to a Linux system, using crontab:

$ crontab -e

or $ sudo crontab -e if you need root privileges

In the crontab file, for example for run this command every 15 minutes, something like this:

# m h  dom mon dow   command
*/15 * * * * python /var/www/myapp/manage.py exporter

More detailed info:

https://docs.djangoproject.com/en/dev/howto/custom-management-commands/
http://es.wikipedia.org/wiki/Cron_%28Unix%29

Enjoy it!

3 Responses
Add your response

In case of using virtualenvs in the server you should use something like this:

cd /home/apps/project/src && /home/user/.virtualenvs/project/bin/python /home/apps/project/src/manage.py cleanup

This way it uses the python libraries installed in the virtualenv.

over 1 year ago ·

Yes, I use a bash script like the following:

#!/bin/bash
cd /var/www/project/management/commands
source ../../ENV/bin/activate
python ../../manage.py exporter
over 1 year ago ·

Very useful article. As I am new to django.

Thanks

over 1 year ago ·