Search code examples
pythoncron

Cronjob not running on Python and Mac


I am trying to test a simple cronjob and when I check if the cronjob has executed, it shows that it has but no file is being created as part of the task.

I have the following script, testjob.py which needs to be executed:

#!/usr/bin/env python3
import datetime

with open('testcron.txt', 'a') as outfile:
    outfile.write('\n' + str(datetime.datetime.now() + 'myname'))

This is the cronjob:

#!/usr/bin/env python3
from crontab import CronTab

my_cron = CronTab(user='myname')
job = my_cron.new(command = 'python /Users/myname/Desktop/customers/cronjob/testjob.py')
#schedule job to run every 2 minutes
job.minute.every(1)
my_cron.write()

How can I troubleshoot this?

link to image with my crontab running via crontab -e: https://i.sstatic.net/pj9Pt.png


Solution

  • You can set up a cron job via crontab -e, which is much better than creating a python script to create a cron job. But anyways.

    1. You can first troubleshoot by actually running your python script and seeing if there are any errors, and if the file is even created.

    2. make sure the user for that cron job has the right permissions to execute the script.

    3. try executing the command: python /Users/myname/Desktop/customers/cronjob/testjob.py directly from your terminal.

    Judging from your response, the reason why its not working is because your script isn't able to open the text file.

    When you're executing the script via: python /Users/myname/Desktop/customers/cronjob/testjob.py, the location of your text file "testcron.txt" depends entirely on where you are executing the script from.

    So basically, unless "testcron.txt" is located in the same path / directory from where you are executing the script, its not going to work.

    You can fix this by changing your cron tab to first navigate to where your text file is, and then run the python script.

    For example, if your "testcron.txt" file is located in /Users/myname/Desktop/customers/cronjob/ then write your cron job as:

    cd /Users/myname/Desktop/customers/cronjob && python ./testjob.py