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.
First, we can use following command to check the current scheduled tasks:
If we want to add new schedule task or edit current schedule, we can run following command:
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:
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
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.
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
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
*/10 * * * * ~/script.sh
*/10 * * * * ~/script.sh >> ~/output.log 2>&1