Scheduling Jobs With Crontab on macOS

Scheduling Jobs With Crontab on macOS

Running scripts on your computer is great. Running them automatically is even better

Image for post$ man crontab

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 do this ?work? every fifteenth minute of every hour, every day.

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 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.

Image for postThe 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 Crontab.guru to generate cron expressions.

Step 3

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 4

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.

Image for postSuccess!

Step 5

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 that 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 of your Python executable by running which python.

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

15

No Responses

Write a response