How to run Django cron in crontab?
I'm not familiar with Django, but I'm seeing the next:
The default Cron's shell is
/bin/sh
.The command
source
is synopsis to.
withinbash
, but not insh
.So
sh -c 'source ...'
will return an error, but&&
means if the previous command return true do the next one, apparently your command fails on this first part. You've redirected only the output of the last command to the log file, so probably it remains blank.In addition I do not think you can successfully source
.bashrc
withinsh
.Within
crontab
, the default vale of the envvar$PATH
is/usr/bin:/bin
. For all commands/scripts, that are located outside of these directories, you should apply the full path; you canexport
a new value of$PATH
, before the job; or even you can use$(which my_command)
instead of justmy_command
.
According to the above, I suppose, your crontab
entry must be something like:
*/5 * * * * bash -c 'source /home/user/.bashrc && source /home/user/django-apps/venv/bin/activate && python /home/user/django-apps/project/manage.py runcrons' > /home/user/cronjob.log 2>&1
- The last part
2>&1
will redirect also the errors to the log file.
The other way, that I would prefer, is to create a simple script that will execute all these commands:
#!/bin/bash
source /home/user/.bashrc
source /home/user/django-apps/venv/bin/activate
python /home/user/django-apps/project/manage.py runcrons
The script should be executable:
chmod +x /path/to/script.sh
And the crontab
will be more simple:
*/5 * * * * /path/to/script.sh > /home/user/cronjob.log 2>&1
If the Cron job is triggered by the crontab of a specific user, and if you want to make the script more portable you can replace /home/user
with the environment variable $HOME
(keep in mind you need to use double quotes, when you work with variables in the shell).
Related videos on Youtube
Vince Gonzales
Updated on September 18, 2022Comments
-
Vince Gonzales over 1 year
I have a Django application which uses django-cron (https://django-cron.readthedocs.io/en/latest/installation.html), and I need to execute
python manage.py runcrons
every 5 mins in AWS EC2 running on Ubuntu. I tried putting this command in crontab -e but nothing happens, is there something I missed?*/5 * * * * source /home/user/.bashrc && source /home/user/django-apps/venv/bin/activate && python /home/user/django-apps/project/manage.py runcrons > /home/bongga-admin/cronjob.log
-
Jos about 5 yearsAlways provide full path names to your executables (in this case
python
). -
Vince Gonzales about 5 yearsI've updated already to: /home/user/django-apps/venv/bin/python, but it's still not running
-
-
Vince Gonzales about 5 yearsThank you!! It works now, although I just had to replace 'source' with './' to make it work inside the script. :)
-
cwhisperer over 3 yearsWhat about the deactivate? When the script is running every 5 minutes, you enter the env each time...