[Django]-Example Cron with Django

13👍

First of all create a custom admin command. This command will be used to add the task to the crontab. Here is an example of my custom command:

cron.py

from django.core.management.base import BaseCommand, CommandError
import os
from crontab import CronTab

class Command(BaseCommand):
    help = 'Cron testing'

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        #init cron
        cron = CronTab(user='your_username')

        #add new cron job
        job = cron.new(command='python <path_to>/example.py >>/tmp/out.txt 2>&1')

        #job settings
        job.minute.every(1)

        cron.write()

After that, if you have a look at the code below, a python script is going to be invoked every 1 minute. Create an example.py file and add it there the functionality that you want to be made every 1 minute.

All is prepared to add the scheduled job, just invoke the following command from the project django directory:

python manage.py cron

To verify that the cron job was added successfully invoke the following command:

crontab -l

You should see something like this:

* * * * * <path_to>/example.py

To debug the example.py, simply invoke this coomand:

tail -f /tmp/out.txt

1👍

You should try to add the following code block at the beginning of your python script which uses anything of the django app.

import sys, os, django
# append root folder of django project
# could be solved with a relative path like os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..') which corresponds to the parent folder of the actual file.
sys.path.append('/path/to/django-project/')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()

Then you should be able to call this script in a cronjob like

* * * * * user /path/to/python /path/to/script
👤zypro

Leave a comment