Detailed explanation of Cron expression
Cron expressions are strings used to define the execution time of a timed task and are widely used in Spring's timed task frameworks such as @Scheduled and Quartz.
Its core is to implement complex scheduling rules through the combination of time fields and wildcard characters.
1. Expression format
The Cron expression consists of 6 or 7 fields, which represent different time units (the 6-bit format is usually used in Spring).
The format is as follows:
Fields | Allowed values | Special characters | illustrate |
---|---|---|---|
Seconds | 0-59 | , - * / | Can be scheduled accurately to seconds |
Minutes | 0-59 | , - * / | |
Hours | 0-23 | , - * / | |
Day | 1-31 | , - * / ? L W | One day of the month |
Month | 1-12 or JAN-DEC | , - * / | |
Week | 0-7 or SUN-SAT (0=Sunday) | , - * / ? L # | Weekly Day (1=MON, 7=SUN) |
Year (Year) | 1970-2099 (optional) | , - * / | Spring is usually omitted |
2. Special character parsing
symbol | effect | Example |
---|---|---|
* | Match any value | 0 * * * * ? Execute 0 seconds per minute |
? | Use only in the day or week fields, meaning "meaningless" | 0 0 0 * * ? Execute at 0 o'clock every day |
- | Range range | 0 0 10-12 * * ? Perform every hour at 10-12 o'clock |
, | Multiple values | 0 0 2,14 * * ? Execute at 2:00 and 14:00 every day |
/ | Step length (interval time) | 0 0/5 * * * ? Execute every 5 minutes |
L | Last Day (only day or week fields) | 0 0 L * * ? Execute at 0 o'clock on the last day of each month |
W | Latest working days (only day field) | 0 0 0 15W * ? Execute on the latest working day on the 15th of each month |
# | Specify the weekdays of the month (weekly only field) | 0 0 0 ? * 6#3 executes on the third Friday of each month |
3. Common examples
expression | illustrate |
---|---|
0 0 12 * * ? | Perform at 12 noon every day |
0 0/5 14 * * ? | Start every 2 pm and perform every 5 minutes |
0 15 10 ? * MON-FRI | Performed from Monday to Friday at 10:15 am |
0 0 0 1 1 ? 2024 | Execute at 0:00 on January 1, 2024 (7-bit expression required) |
0 0 8-18/2 ? * MON | Perform every 2 hours every Monday from 8 am to 6 pm |
0 0 0 L * ? | Execute at 0 o'clock on the last day of each month |
0 0 0 15W * ? | Perform the most recent working day on the 15th of each month |
0 0 0 ? * 6#3 | Implemented on the third Friday of every month at 0:00 |
4. Key rules
1. The mutual exclusion between day and week
- If you specify both day and weekly, you need to ignore one of the fields.
- ✅ Correct: 0 0 0 ? * MON (execute every Monday, ignore the day)
- ❌ Error: 0 0 0 * * MON (Day and weekly take effect at the same time, may conflict)
2. Abbreviation of month and week
- Month: JAN, FEB, MAR… DEC
- Week: SUN, MON, TUE… SAT
- A combination of L and W
- LW represents the last working day of the month.
- L-3 means the third day to the end.
- Year field (optional)
- Spring's @Scheduled does not support the year field, and requires a 6-bit expression.
5. Dynamic and complex scenarios
1. Dynamic Cron expression
- It can be read from the configuration file in Spring by @Scheduled(cron = "${}").
- Combined with the database dynamic update task:
@Scheduled(cron = "#{@()}") public void dynamicTask() { // Business logic}
2. Avoid the peak of the mission
- Add random delay (avoid multiple tasks being triggered simultaneously):
@Scheduled(cron = "0 #{T().current().nextInt(55)} * * * ?") public void randomMinuteTask() { // Random minutes per hour}
3. Leap year treatment
- Cron cannot directly deal with leap years, so it needs to be judged in combination with the code logic.
6. Debugging and Verification
1. Online Tools
- Crontab Guru: Quickly validate expressions.
- CronMaker: Generate expressions and view the next execution time.
- Log debugging
- Add a log in the task method to see if the trigger time is as expected:
@Scheduled(cron = "0 0/5 * * * ?") public void logTask() { ("Task execution time: {}", ()); }
7. FAQ
1. Why is the task not executed?
- Check whether to add
@EnableScheduling
。 - Check if the Cron expression is correct (such as Spring does not support the year field).
- Check the time zone settings (the server time zone is used by default, which can be modified through the zone property).
2. How to implement execution every N days?
-
Plan 1
:use0 0 0 */N * ?
(like0 0 0 */5 * ?
Perform every 5 days). -
Plan 2
: Record the last execution time through code.
3. Idepotency in distributed environments
Using Redis distributed locks:
@Scheduled(cron = "0 0 * * * ?") public void distributedTask() { if (("taskLock", 10)) { try { // Business logic } finally { ("taskLock"); } } }
Summarize
Cron expressions implement flexible timing rules through concise syntax, but attention should be paid to the applicable scenarios of field mutex and special characters.
In complex services, dynamic configuration, distributed locking and log monitoring can be combined to ensure stable task execution.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.