using cron on OSX to run a Python file (or any other script)
I just figured out how to use cron on OSX. Here’s some quick notes on what I learned.
Cron is a little command line tool you can use to schedule tasks on *nix systems. Although some sources suggest that Apple has deprecated the use of cron in favour of launchd, it is still supported and provieds a nice cross (*nix) platform solution. This works nicely for me because I’m working on something I later want to run on a Raspberry Pi.
A cron snippet has 5 positional time codes, followed by a command to execute. The below diagram nicely captures what every position (indicated by the asterisks *) stands for. You can read more about cron here.
┌───────────── minute (0 - 59) │ ┌───────────── hour (0 - 23) │ │ ┌───────────── day of month (1 - 31) │ │ │ ┌───────────── month (1 - 12) │ │ │ │ ┌───────────── day of week (0 - 6) (Sunday to Saturday; │ │ │ │ │ 7 is also Sunday) │ │ │ │ │ │ │ │ │ │ * * * * * command to execute
Note that the command executed by cron by default can only include standard command line tools (that are loaded from /usr/bin:/bin). You can add more directories to your PATH as part of your cron file as explained here.
Some examples cron snippets (from Ole Michelsen):
0 1 * * 1-5 /bin/execute/this/script.sh
*/10 * * * * /bin/execute/this/script.sh
*/10 * * * * /bin/execute/this/script.sh >> /var/log/script_output.log 2>&1
To add a task to the the list of cron jobs you use the crontab command. To edit (and create if necessary) a cron job use:
This opens a (at this stage probably empty) file in the Vim editor. I tried for a while to get it to open in Sublime Text but couldn't get it to save properly. The Vim commands seem obscure if you havent used it before, but don't panic, you'll only need a few.
First press 'i' to enter INSERT mode.
type / paste your cron task code
press ESC to leave INSERT mode.
press 'ZZ' (capitals) to save and exit Vim.
Testing if your cron job is working
This Stack Exchange answer suggested testing with a plain command line utility (one that cron has access to by default):
* * * * * /usr/bin/logger "hello world"
this will log the text "hello world" to your system console every minute (open it by typing "console" into spotlight).
... and now running a python file
Once this was working, I moved on to get it to run a Python script I have prepared.
Adding python3 /absolute/path/to/my/python_file.py as the comman to execute by cron didn't work for me, probably because my python3 isn't part of cron's default PATH. To solve this I made the python script executable by the command line (shell) by finding the path to my python3 installation
which python3 /usr/local/bin/python3
and adding this as the first line of my python file:
Now I'm was able to simply add the the absolute path to my python file as the command to execute in my cron job:
* * * * * /absolute/path/to/my/python_file.py