I have thought about to write this article for a long time. At the beginning, I wanna append this tips on post “Work on Mac“. Finally I decide to write this article because this topic covers quite lots of content, a separate article will be better. As we know, on Unix or Linux, we can use cron to schedule tasks. But on Max OS, it’s better to use crontab utility.

crontab

First, we can use following command to check the current scheduled tasks:

crontab -l

If we want to add new schedule task or edit current schedule, we can run following command:

crontab -e

With above command, the system will launch the default editor (VI in my system) to edit the schedule. The schedule task format is the same as cron in Linux/Unix:

* * * * *  command to execute
| | | | |
| | | | |----day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
| | | |------month (1 - 12)
| | |--------day of month (1 - 31)
| |----------hour (0 - 23)
|------------min (0 - 59)

If we want to execute several commends, we can use && to connect them:

0 12 * * *  cd ~/folder && ./backup.sh

If the schedule is very complicated and it’s hard to edit, we can write all schedule tasks in one file, then use following command to launch those tasks:

crontab file

FAQ

Question:
When I setup my schedule task which will pipe the output into a file, I cannot find the cron result log file. Here is the schedule task:

* * * * * env > a.output

Answer:
Basically, crontab will treat home folder as the current path to run the schedule tasks. If you don’t specify the absolute path, all output files will be located in home folder. With above example, we can find the file a.output in the home folder.

Question:
After my schedule task is executed, I get following error in my mail:

/bin/sh: python3: command not found

Here is my schedule task:

* * * * * cd ~/script && python3 my.py

Answer:
By default, crontab has its own PATH environment variable. Therefore, before the system execute the schedule tasks, you can set the PATH first. You can use following example code:

PATH=/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
* * * * * cd ~/script && python3 my.py

Crontab Schedule Time Tips

Here are some handy tips for you to schedule your tasks with crontab on Mac OS.

  • Execute the task on every workday at 1AM
  • 0 1 * * 1-5 ~/script.sh
    
  • Execute the task every 10 minutes
  • */10 * * * * ~/script.sh
    
  • Log output to file
  • */10 * * * * ~/script.sh >> ~/output.log 2>&1
    
Previous PostNext Post

Leave a Reply

Your email address will not be published. Required fields are marked *