Example Cron with Django

2019-06-14 08:39发布

问题:

I've serched among the internet 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 shecudled task with cron?

回答1:

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


回答2:

Scheduled task can be done through celery.

Celery is a task queue with focus on real-time processing, while also supporting task scheduling.



回答3:

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