7

I have been trying a long for creating a periodic task in Django but there are lot of version constraints and not a clear explanation.

4 Answers4

5

I recommend Celery. What is Celery?

Celery supports scheduling tasks. Check this doc

Jrog
  • 1,469
  • 10
  • 29
5

First of all, you want to create a management command following this guide. https://docs.djangoproject.com/en/2.1/howto/custom-management-commands/

Say we want to run the closepoll command in the example every 5 minutes. You'll then need to create a script to run this command.

Linux / MacOS:

#!/bin/bash -e
cd path/to/your/django/project
source venv/bin/activate  # if you use venv
python manage.py closepoll  # maybe you want to >> /path/to/log so you can log the results

store the file as run_closepoll.sh, run chmod +x run_closepoll.sh in command line

Now we can use crontab to run our command

run crontab -e in your command line add this line: */5 * * * * /path/to/run_closepoll.sh Now the command will run every 5 minutes. If you're not familiar with crontab, you can use this website https://crontab-generator.org/

Windows:

Same content as the above example, but remove the first line and save as run_closepoll.bat

In your start menu, search for Task Scheduler, follow the instructions on the GUI, it should be pretty simple from there.

for more info about the task scheduler, see here: https://learn.microsoft.com/en-us/windows/desktop/taskschd/using-the-task-scheduler

rabbit.aaron
  • 2,369
  • 16
  • 25
2

This blog explains clearly

https://medium.com/@yehandjoe/celery-4-periodic-task-in-django-9f6b5a8c21c7

Thanks!!!

  • 1
    It would be much more useful for the readers if you'd at least mention what is the link about. It suggests to use Celery (which was already suggested in the earlier answer). For the small projects Celery is too heavy IMO. – The Godfather Nov 09 '20 at 09:19
0

I'm using django-cron and It works as expected. The only caveat is that you have to set a Cron job in the Linux system to run the command python manage.py runcrons.

Genarito
  • 3,027
  • 5
  • 27
  • 53