1

I've django application which uses env variables defined in .bashrc file. The django app is getting the values defined in .bashrc file.

I need to run a python management command in crontab. Usually this is pretty simple to define. Either you can define the management command in script and add it cron or use the command directly in the cron.

But in this can cron is not getting the values of env variables defined in .bashrc file. I've tried almost every doc i found but still its not wokring.

here is the script i used:

WORKON_HOME=/home/ubuntu

PROJECT_ROOT=/home/ubuntu/projects/

. $WORKON_HOME/virtuals/bin/activate

cd $PROJECT_ROOT

python manage.py COMMAND

and in the cron tab i used:

*/2 * * * * /home/ubuntu/test.sh

This setup was working in all other cases.Now there is error when cron is executed. But the script works when manually executed.

Nijo
  • 772
  • 1
  • 8
  • 27

3 Answers3

1

A cron-job is not an interactive shell. So .bashrc will not get sourced. You have to do that manually either in your script or in the crontab itself.

Something like that should do it:

*/2 * * * * source /home/ubuntu/.bashrc ; /home/ubuntu/test.sh
Moritz Sauter
  • 167
  • 1
  • 11
  • i've already tried it. But the django env variables are not working in cron. i redirected the output to a file and there was env variables missing in django app error. – Nijo Dec 21 '16 at 15:43
0

found the answer: Cron not running django command

I defined these values manually inside the cron script.

Community
  • 1
  • 1
Nijo
  • 772
  • 1
  • 8
  • 27
0

If you are using Ubuntu >=18.0, try with following changes. I am assuming you have successfully integrated django-crontab with your django application or manually. Now, access to your server via ssh and type "crontab -e", You will see your cronjobs are defined here. Add Your Environment Variables just above your cronjob and save the file using CTRL+o & CTRL+x. Please have a look at the following piece of lines-

DB_NAME = "database name"
DB_USER = "user"
DB_PASSWORD = "db password"
SECRET_KEY = "************************"

*/1 * * * * /home/sms/sms/env/bin/python /home/sms/sms/sms- 
 backend/website/manage.py crontab run 446aeeebac8c8f82d9e01bb662dc9b21 > 
 /tmp/scheduled_job.log # django>

Hope you get rid of it.