Zsh Shell Tutorial #24: Automate with cron & launchd
Video: Zsh Shell Tutorial #24: Automate with cron & launchd by Taught by Celeste AI - AI Coding Coach
Watch full page →Zsh Shell Tutorial #24: Automate with cron & launchd
Scheduling tasks in Zsh can be efficiently managed using cron on Linux and launchd on macOS. This tutorial covers how to write cron syntax, manage crontabs, use common cron patterns, and create launchd plist agents for macOS automation.
Code
# Example: Edit your crontab with the following command
crontab -e
# Add a cron job to run a script every day at 2:30 AM
30 2 * * * /path/to/your/script.sh
# Common cron time fields:
# * * * * * command to execute
# - - - - -
# | | | | |
# | | | | +----- day of week (0-7) (Sunday=0 or 7)
# | | | +------- month (1-12)
# | | +--------- day of month (1-31)
# | +----------- hour (0-23)
# +------------- minute (0-59)
# Example: Run a command every 15 minutes
*/15 * * * * /path/to/your/command
# macOS launchd plist example (save as ~/Library/LaunchAgents/com.example.task.plist):
#
#
#
#
# Label
# com.example.task
# ProgramArguments
#
# /path/to/your/script.sh
#
# StartCalendarInterval
#
# Hour
# 2
# Minute
# 30
#
# RunAtLoad
#
#
#
# Load the plist with launchctl
launchctl load ~/Library/LaunchAgents/com.example.task.plist
Key Points
- Cron uses a five-field syntax to schedule tasks by minute, hour, day, month, and weekday.
- Crontab files can be edited with
crontab -eto add, modify, or remove scheduled jobs. - Common cron shortcuts like
*/15enable running jobs at regular intervals, such as every 15 minutes. - On macOS, launchd uses plist files to define scheduled jobs with more flexible options and integrates with system startup.
- Use
launchctl loadandlaunchctl unloadto manage launchd agents without rebooting.