In UNIX-like operating systems, the cron daemon runs continuously in the background, waking up every minute to check if there are scheduled system chores, like database backups, cache flushing, or report generation, that need to run.
Developers configure these schedules using **crontab** files. However, cron's five-field format is famously cryptic, and minor typos can cause tasks to trigger at incorrect times or loop continuously, exhausting system resources. Let's master crontab syntax.
1. The Five Cron Fields
A standard cron expression consists of five space-separated fields representing different time parameters. From left to right, the fields correspond to:
- Minute (0 - 59): The minute of the hour when the command executes.
- Hour (0 - 23): The hour of the day (24-hour clock).
- Day of Month (1 - 31): The day of the calendar month.
- Month (1 - 12 or JAN-DEC): The calendar month.
- Day of Week (0 - 6 or SUN-SAT): The day of the week (0 and 7 usually both represent Sunday).
# * * * * * command_to_execute
# │ │ │ │ │
# │ │ │ │ └─ Day of Week (0 - 6)
# │ │ │ └──── Month (1 - 12)
# │ │ └─────── Day of Month (1 - 31)
# │ └────────── Hour (0 - 23)
# └───────────── Minute (0 - 59)
2. Special Cron Operators
To write flexible schedules, you combine numbers with special wildcards and operators:
- Asterisk
*: Matches any value in that field. For example,*in the hour field means "run every single hour". - Comma
,: Specifies a list of discrete values. For example,1,15,30in the minute field means "run at minutes 1, 15, and 30". - Hyphen
-: Defines a range of values. For example,9-17in the hour field means "run every hour from 9 AM through 5 PM". - Slash
/: Indicates increments or step values. For example,*/15in the minute field means "run every 15 minutes".
3. Non-Standard Operators & Shortcuts
Many modern cron implementations (like Vixie Cron) support shortcuts to replace the five fields entirely:
@hourly: Equivalent to0 * * * *(runs at the start of every hour).@daily: Equivalent to0 0 * * *(runs at midnight every day).@weekly: Equivalent to0 0 * * 0(runs at midnight on Sunday).@reboot: Executes the command once at startup.
4. Troubleshooting Common Scheduling Mistakes
When setting up production crontabs, keep the following security and design considerations in mind:
- Timezone Mismatches: The cron daemon uses the system's local hardware timezone by default. If your servers are in UTC and your dev environment is local, cron will fire offset. Always check system time via the
datecommand. - Overlapping Runs: If a script scheduled to run every 5 minutes (
*/5 * * * *) takes 6 minutes to complete, a new instance will spawn before the old one finishes. Prevent this by wrapping your commands in lock tools likeflockortimeout.