Thursday, May 26, 2022

[SOLVED] How to manually create a cron job to run a Django script?

Issue

I have been trying to run some code as a cron job using Django. There are a number href="https://github.com/jgorset/django-kronos" rel="nofollow noreferrer">of packages that help do this, but they do not seem to support the latest Django version (4.0). Instead of continuing to search for packages, I was wondering if it is possible for me to simply write a python script within my Django folder structure, and manually configure a cron job to run this. Something like setting up:

*/30 * * * * python3.8 /var/djangoproject/crons/cron.py

Is this possible? Is there any drawback or risk in doing it like this instead of using a package that is made for this? I don't see anyone recommending this so before implementing it I wanted to see if this is a good idea.


Solution

Turns out this is quite easy, and can be achieved by using custom django-admin commands. You basically add a management/commands folder to the project, and add a python script to that folder with a specific structure (see documentation). Say you call the file cron.py. Then a cron can be configured as such:

*/30 * * * * python3.8 /var/djangoproject/manage.py cron


Answered By - user74934
Answer Checked By - Pedro (WPSolving Volunteer)