Understanding Cron Expression Syntax: A Developer's Guide
A cron expression is a string consisting of five or six fields separated by white space that represents a schedule for executing a software task. Originally created for the Unix cron utility, it is now widely supported by cloud platforms like AWS EventBridge, Google Cloud Scheduler, Kubernetes, and backend frameworks like Spring, Node-cron, and Quartz.
The 5-Field Cron Structure
Standard cron syntax consists of five parts, ordered as follows:
- Minute (0 - 59): The exact minute of the hour the task will trigger.
- Hour (0 - 23): The hour of the day (in 24-hour format) the task runs.
- Day of Month (1 - 31): The specific date of the month.
- Month (1 - 12 or JAN-DEC): The month of the year.
- Day of Week (0 - 6 or SUN-SAT): The specific day of the week (where 0 or 7 is Sunday).
Common Special Characters in Cron Syntax
To write advanced scheduling rules, cron supports special character syntax:
- Asterisk (*): Represents "every" or "all values". E.g., a
*in the month column means every month. - Comma (,): Specifies a list of discrete values. E.g.,
1,3,5in the day-of-week column means Mon, Wed, and Fri. - Hyphen (-): Defines a range of values. E.g.,
9-17in the hour column means every hour from 9 AM to 5 PM. - Slash (/): Specifies increments or steps. E.g.,
*/10in the minute column means every 10 minutes.
Examples of Common Schedules
0 0 * * *- Run once every day at midnight.*/15 * * * *- Run every 15 minutes, every day.0 9-17 * * 1-5- Run at the top of every hour during business hours (9 AM - 5 PM) on weekdays.0 0 1 1 *- Run once a year at midnight on January 1st.