k5p6ag
Last Updated: February 25, 2016
·
7.141K
· emi420
Image

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!

Say Thanks
Respond

3 Responses
Add your response

244
Yo nueva

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 ·
246
Image

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 ·
11522
00dab5265d7379b849eb8d81995b8ab3

Very useful article. As I am new to django.

Thanks

over 1 year ago ·
Filed Under