To schedule a shell script to run at specific times, use either launchd
or cron
.
You should use launchd
instead of cron
to schedule tasks. With launchd
, if a task is skipped because the computer is shut off or asleep, the task is added to the queue when the computer comes back online.
To use launchd
to schedule timer-based jobs, use the StartCalendarInterval
or StartInterval
key.
For more information about launchd
, see its man page.
The cron
daemon executes scheduled commands defined in crontab files. The cron
daemon searches the /usr/lib/cron/tabs/ folder for crontab files named after accounts in /etc/passwd, and loads the files into memory. The cron
daemon also searches the /etc/crontab/ folder for crontab files, which are in a different format. cron
then cycles every minute, examining stored crontab files and checking each command to see if it should be run in the current minute.
When commands execute, output is mailed to the owner of the crontab file or to the user named in the optional MAILTO environment variable in the crontab file.
You use the crontab
tool to install, uninstall, or list the tables used to drive the cron
daemon. Users can have their own crontab file.
To configure your crontab file, use the crontab -e
command. This opens an empty crontab file in vim
edit mode.
Here’s an example of a crontab file to enter:
SHELL=/bin/sh
PATH=/bin:/sbin:/usr/bin:/usr/sbin
HOME=/var/log
#min hour mday month wday command
30 18 * * 1-5 diskutil repairPermissions /Volumes/MacHD
50 23 * * 0 diskutil repairVolume /Volumes/MacHD
In this example, the first entry repairs disk permissions for the MacHD volume at 18:30 every day, Monday through Friday:
30 18 * * 1-5 diskutil repairPermissions /Volumes/MacHD
The second entry schedules a repair volume operation to run at 23:50 every Sunday:
50 23 * * 0 diskutil repairVolume /Volumes/MacHD