Search code examples
pythondjangocronscheduled-tasks

Example Cron with Django


I've searched the internet for a working example of a scheduled job in Django. But I can only find how to do it, but no example is given. Can someone share a working example of the Django framework running a scheduled task with cron?


Solution

  • 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