python-3.xcronubuntu-18.04django-1.11django-kronos

Django task not running using crontab


I am using django-kronos to create a cron job and it is running fine when I run it manually. But it is not running in case of crontab.

Below is my code to test if it is working:

settings.py

ENV_PATH = os.path.join(BASE_DIR, '.env')

# Adding KRONOS PROPERTIES
KRONOS_PREFIX = '{} '.format(ENV_PATH)
KRONOS_POSTFIX = '>> /var/log/cron.log 2>&1'

I have my passwords in .env file. Hence I have used KRONOS_PREFIX to export those variables first. KRONOS_POSTFIX is used to add logs to my cron.

cron.py

import kronos

@kronos.register('* * * * *')
def test_task():
    print("IT WORKS....")

Commands:

$ python manage.py showtasks

* List of tasks registered in Kronos *
>> Kronos tasks
    >> test_task
>> Django tasks

$ python manage.py installtasks
1 task removed, 1 installed.

crontab -l

* * * * * /home/sam/..../.env  /home/sam/.../venv/bin/python /home/sam/.../manage.py runtask test_task  --settings=my_project.settings >> /var/log/cron.log 2>&1 # kronos:4f383ee5e8844285d6ac6dc78196e377

It works when I run the command mentioned in crontab manually and logs the output as well. I checked several articles online without any success.

I found this digitalocean article somewhat similar but this is also not working in my case.

Any help is much appreciated.

Thanks.


Solution

  • After checking several articles for a few hours and debugging, I found out that the main issue was with the source .env i was using. crontab was not able to export the environment variables using that command. So, I decided to create another file with the name .env_constants and update KRONOS_PREFIX as follows:

    settings.py

    KRONOS_PREFIX = 'env - `cat {}` '.format(os.path.join(BASE_DIR, '.env_constants'))
    

    .env_constants

    DB_NAME=db_name
    DB_USER=db_user
    DB_PASSWORD=db_password
    DB_HOST=localhost
    DB_PORT=port_no
    

    And my cron now looks like:

    * * * * * env - `cat /home/sam/.../.env_constants`  /home/sam/.../venv/bin/python /home/sam/.../manage.py runtask test_task  --settings=my_project.settings >> /var/log/cron.log 2>&1 # kronos:4f383ee5e8844285d6ac6dc78196e377
    
    

    Now it is running fine.