Last Updated: February 25, 2016
· 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:


from 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 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/ exporter

More detailed info:

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/ 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:

cd /var/www/project/management/commands
source ../../ENV/bin/activate
python ../../ exporter
over 1 year ago ·

Very useful article. As I am new to django.


over 1 year ago ·