Overview
Cron expressions are used everywhere: Linux scheduled tasks, Spring Boot scheduling, cloud automation, and CI jobs. This guide explains the syntax and provides ready-to-use examples.
Cron Expression Structure
A standard Unix cron expression has five fields. Quartz, commonly used in Java applications, uses six or seven fields.
Unix Five-Field Format
minute hour day-of-month month day-of-week
* * * * *
Quartz Six-Field Format
second minute hour day-of-month month day-of-week
* * * * * *
Field Values
| Field | Unix position | Quartz position | Allowed values |
|---|---|---|---|
| Second | — | 1st | 0–59 |
| Minute | 1st | 2nd | 0–59 |
| Hour | 2nd | 3rd | 0–23 |
| Day of month | 3rd | 4th | 1–31 |
| Month | 4th | 5th | 1–12 or JAN–DEC |
| Day of week | 5th | 6th | 0–6 (0 = Sunday) or SUN–SAT |
Special Characters
| Character | Meaning | Example |
|---|---|---|
* | Any value | * in minute means every minute |
, | List of values | 1,15,30 means minutes 1, 15, and 30 |
- | Range | 9-17 means hours 9 through 17 |
/ | Start and interval | 0/5 means every 5 units starting at 0 |
? | No specific value | Used in day-of-month or day-of-week |
L | Last day | L in day-of-month means last day of month |
W | Nearest weekday | 15W means nearest weekday to the 15th |
# | Nth weekday | 2#1 means first Monday of the month |
? is only used in the day-of-month and day-of-week fields because these two fields can conflict. If one is specified, the other should usually be ?.
Common Quartz Examples
| Schedule | Quartz expression |
|---|---|
| Every day at 10:15 AM | 0 15 10 ? * * |
| Every day at 10:00, 14:00, and 16:00 | 0 0 10,14,16 * * ? |
| Every hour at minute 40 from 9 AM to 5 PM | 0 40 9-17 * * ? |
| Every 30 minutes from 10 AM to 4 PM | 0 0/30 10-16 ? * 2 |
| 15th day of every month at 10:15 AM | 0 15 10 15 * ? |
| Last day of every month at 10:15 AM | 0 15 10 L * ? |
| Every Wednesday in March at 2:00 PM and 2:30 PM | 0 0,30 14 ? 3 WED |
Common Unix Examples
| Schedule | Unix expression |
|---|---|
| Every day at 9:30 AM | 30 9 * * * |
| Every 5 minutes | */5 * * * * |
| Every Monday at 8:00 AM | 0 8 * * 1 |
| First day of every month at midnight | 0 0 1 * * |
Linux Crontab Example
# Edit the current user's cron jobs
crontab -e
# Add a job: back up the database every day at 2:30 AM
30 2 * * * /home/user/backup.sh >> /var/log/backup.log 2>&1
# List current cron jobs
crontab -l
# Remove all cron jobs
crontab -r
Always redirect output to a log file. Otherwise, job output is lost and troubleshooting becomes difficult.
Common Mistakes
- 0 and 7 both mean Sunday in some systems, but behavior can vary. Use 0 for consistency.
- Do not specify both day-of-month and day-of-week with fixed values. Use
?for one of them. - Quartz and Unix have different field counts. Spring Boot uses the six-field Quartz format by default, where the first field is seconds.
- Cron does not use the same environment as your shell. Use absolute paths or set
PATHinside crontab.
