Run a shell script at specific times
To schedule a shell script to run at specific times, use either launchd
or cron
.
Schedule tasks with launchd
Use
launchd
instead ofcron
to schedule tasks. Withlaunchd
, if a task is skipped because the computer is shut off or in sleep, the task is added to the queue when the computer comes back online.To use
launchd
to schedule timer-based jobs, use theStartCalendarInterval
orStartInterval
key.For more information about
launchd
, see its man page.
Use cron to schedule a task
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 edit mode.Here’s an example of a crontab file:
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