Cron Expressions Demystified
Cron is Unix's task scheduler, and its expression syntax is one of those things you look up every single time. This guide aims to make it stick.
The Format
┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-7, 0 and 7 = Sunday)
│ │ │ │ │
* * * * *Five fields, left to right, separated by spaces. That's it.
Common Patterns
| Expression | Meaning |
|---|---|
* * * * * | Every minute |
0 * * * * | Every hour (at minute 0) |
0 0 * * * | Every day at midnight |
0 9 * * 1-5 | Weekdays at 9am |
0 0 1 * * | First of every month at midnight |
*/15 * * * * | Every 15 minutes |
0 */2 * * * | Every 2 hours |
30 4 * * 0 | Sundays at 4:30am |
Special Characters
*— any value,— list:1,3,5= 1st, 3rd, 5th-— range:1-5= Monday through Friday/— step:*/10= every 10 units
Real Examples
# Database backup at 3am daily
0 3 * * * /scripts/backup-db.sh
# Clear temp files every Sunday at 4am
0 4 * * 0 find /tmp -mtime +7 -delete
# Send report every weekday at 8:30am
30 8 * * 1-5 /scripts/send-report.sh
# Docker image prune weekly (what we set up earlier!)
0 4 * * 0 docker image prune -f
# Rotate logs at midnight on 1st and 15th
0 0 1,15 * * /scripts/rotate-logs.shGotchas
- Timezone: Cron runs in the server's timezone. Use
TZ=UTCprefix or set the timezone in the crontab - PATH: Cron has a minimal PATH. Use full paths (
/usr/bin/dockernot justdocker) - Output: Redirect output or cron will try to email it:
>> /var/log/cron.log 2>&1 - Day of month + day of week: If both are set, they're OR'd (not AND'd).
0 0 13 * 5= every Friday AND every 13th
Build visually: Cron Expression Generator — set minute, hour, day and see the expression + human-readable description.