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!
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.
work.sh works properly and is in a place where you keep your helper scripts. For me, they’re usually in
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.
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
You can also use sites like this to generate cron expressions.
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.
- Make sure
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.
That’s it! All done!
- To see your active cron jobs you can use the
- 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.
- 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.pyinstead of
- You can find out the location for your python executable by running
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.