Scheduling jobs with crontab on macOS

Running scripts on your computer is great. Running them automatically is even greater. Automatic running can be achieved on macOS (and Linux) by creating cron-jobs!

$ man crontab

Let’s make an example job. Suppose you want to run a script called work.sh which does some work for you — doesn’t really matter what the work is. You want to this “work” every fifteenth minute of every hour, everyday. Here’s what I would do to achieve this.

Step 1

Make sure work.sh works properly and is in a place where you keep your helper scripts. For me, they’re usually in ~/.scripts.

Step 2

Next, fire up the terminal and run crontab -e. This is should open up a file in vim for you. This file is essentially where you can list out your cron jobs — each job on its own line.

The result of crontab -e.

Setting cron jobs requires a specific format.

* * * * * command
* - minute (0-59)
* - hour (0-23)
* - day of the month (1-31)
* - month (1-12)
* - day of the week (0-6, 0 is Sunday)
command - command to execute
(from left-to-right)

You can also use sites like this to generate cron expressions.

Step 4

Once you’re on the vim screen, hit i to put the editor into INSERT mode and then put 0,15,30,45 * * * * cd ~/.scripts && ./work.sh on the first line. This expression evaluates to what we want the job to be.

Gotchas —

  • Make sure work.sh is executable.

Step 5

After typing out the cron expression, hit esc and then type :wq to save and exit vim. If you did everything properly, you should see the terminal tell you that it installed a new crontab. In case it tells you that the setup failed, double check your cron expression.

Success!

Step 6

That’s it! All done!


Bonus

  1. To see your active cron jobs you can use the crontab -l command.
  2. If you want to, for instance, run a python script using a cron job, you’ll have to deal with some added complexity. The way you should set this up is by having two scripts — the python script and an executable shell script which runs the python script. This way you can keep your cron expression short and succinct and even add some modularity.
  3. In your call to execute the python script in the scenario mentioned above, make sure you point to the location of the python executable in the shell script and not the python alias. So, it should be something like usr/bin/python script.py instead of python script.py.
  4. You can find out the location for your python executable by running which python.

Hope this post helped! Good luck and keep on hacking!


If you liked this post, 👏 for it; follow me if you want more such posts!

If you wanna chat, you can find me on Twitter here.