How to run a Python script every hour using Cron on Ubuntu 14

Want to have a Python script run every hour on your Ubuntu server? It's easy to setup a Cron job to do this.

Get your Python script ready

It's convenient to add a shebang to your Python script, so you can use it as a shell script:

#!/usr/bin/env python3

#!/usr/bin/env python3

Open CronTab

Run this command:

crontab -e

You may be asked to choose an editor. If so, please choose the editor of your choice (I choose vi. An editor will open:

vim opened with a crontab file

At the bottom of the file, we can add a line to run a Python script every hour:

crontab file with a line added to it

The line we added above was this:

* */1 * * * cd /my/python/script/dir && /my/python/script/dir/myscript.py

As shown in this post, you'll probably want to change directories to where you typically run your script. Otherwise your Python script might not find needed modules.

How do I run it every minute?

Move the */1 into the minutes spot:

*/1 * * * * cd /my/python/script/dir && /my/python/script/dir/myscript.py

My cron job isn't running successfully. What do I do?

Make sure the exact command can be run manually without errors.

Set the task to run every minute.

As shown here, try piping your command output to a file:

*/1 * * * * cd /my/python/script/dir && /my/python/script/dir/myscript.py >> /my/python/script/dir/results.txt 2&>1

Where's the error log?

As recommended here, run the following command to view errors:

grep CRON /var/log/syslog

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.