4

I have setup a cron job by using django crontab. As per defined in documentation I defined a test job in cron.py and defined it to run in 1 minute interval in settings.py.

#cron.py
def test_cron_run():
    print("\n\nHello World....!! ",timezone.now())

#settings.py
INSTALLED_APPS = [
    'material.theme.cyan',
    'material',
    'material.admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'django_crontab',
]

CRONJOBS = [
    ('*/1 * * * *', 'myapp.cron.test_cron_run','>>'+os.path.join(BASE_DIR,'log/debug7.log')),
]

I have added the cron jobs by running python3 manage.py crontab add. Also the job is added as I can see if I run, python3 manage.py crontab show However I cannot see any log file being generated. Is there any way to debug this, the os logs or something?

Paras
  • 3,191
  • 6
  • 41
  • 77
  • 1
    Is it possible that you're missing a space after the `>>`? – Shinra tensei Jan 31 '19 at 15:01
  • what if using `('*/1 * * * *', 'myapp.cron.test_cron_run', '>> test.log'),` instead? – seuling Jan 31 '19 at 15:09
  • Yes it runs if I run it forcefully by run command passing the hash value of the job and prints on console, however no log file generated, anyway, is there a way I can hook a debugger to my code to debug my django code? – Paras Jan 31 '19 at 15:15

3 Answers3

4

To combine the tips given here, this is how it worked for me:

import os

CRONJOBS = [
    ('* * * * *', 'myapp.cron.test_cron_run', '>> ' + os.path.join(BASE_DIR,'log/debug7.log' + ' 2>&1 '))
]

Additional notes

  • The directory needs to exist and you need write permission
  • After each change of CRONJOBS, run python3 manage.py crontab add twice
  • Without the 2>&1, error messages from python are not logged as they are written to STDERR
  • Check what is actually written to your crontab with crontab -l
  • If it is not working, you may have a mail from cron. Depending on your system, read it with mail.
Den
  • 547
  • 1
  • 6
  • 15
1

Maybe just try adding 2>&1 at the end of you cron job, it will redirect the error output to the standard output.

Taek
  • 1,004
  • 7
  • 20
1

I had the same problem. I could only get it to work by including the direct path to the logfile and creating it ahead of time

  • Even though, the file had automatically being created, nothing was being written to it. The solution is as you mentioned to create the file yourself. – Susmit May 31 '22 at 10:40