Python – How to Fix Python Script Not Running as Cronjob

croncrontabpython

I have tried everything and I've seen other questions here regarding this but I cannot for the life of me run a python script as a cronjob.

I've tried the following.

* * * * * /usr/bin/python /home/myhome/myscript.py

All myscript.py does is a sleep for 30 seconds so I can check processes if it is running but I have yet to see it.

import time
time.sleep(30)

What am I missing? Shouldn't this run? I've even tried opening a file in /tmp and outputting there but no luck. I'm assuming its some environment variable issue but im not sure where to start.

BTW this runs fine on command line.

Best Answer

Yes, this should run fine, assuming when you say "it runs fine on the command line" you're literally pasting the same command from the crontab entry. Things to check:

  1. Is the cron daemon actually running? (Run pidof cron)
  2. If it is running, try restarting it. (Depends on your flavour of Unix, but something like service cron restart or /etc/init.d/cron restart)
  3. If your script still doesn't run, check everything in /var/log for appropriate output - the specific file depends on your syslog configuration, but /var/log/messages and /var/log/syslog are good options if /var/log/cron doesn't exist.

Note: You'll need to be root to do most of these things - if you don't have access then you'll need to speak to the person who administers the machine.

Also, when you say you open a file in /tmp, that's probably the most reliable thing you can do to ensure it's running. Right at the start of your script (before imports or anything) add this:

with open("/tmp/testfile", "a") as fd:
    fd.write("I am running\n")

You can also check if your crontab is being correctly installed - it should be placed in something like /var/spool/cron/crontabs (that's on Ubuntu Linux, it may differ on different Unix flavours). You should see a file in there with your username which should contain your entry.

Finally, if you get really desperate you could strace your cron process to see what it's doing:

sudo strace -f -p `pidof cron`

You don't need to worry too much about the specifics, but it should be doing something every minute. If it's not then something's going quite wrong.

Related Question