Spring Scheduled Tasks Cron Guide
The time configuration for Spring scheduled tasks is specified using a Cron expression.
A Cron expression is a string that consists of 6 or 7 spaced fields representing seconds, minutes, hours, day of month, month, day of week, and year (optional). The specific syntax rules are as follows:
- Seconds (0-59)
- Minutes (0-59)
- Hour (0-23)
- Date (1-31)
- Months (1-12 or JAN-DEC)
- Use the numbers 1-7 to represent the days of the week, with 1 being Sunday and 7 being Saturday.
- Year (optional)
Here are some common examples of Cron expressions:
- “0 * * * * *”: run every minute
- “0 0 * * * *”: Run every hour on the hour.
- “0 0 12 * * *”:Run once every day at noon.
- At every hour from 8 AM to 6 PM every day.
- “Every Monday to Friday at 12:00 PM”
- “0 0 12 ? * 6L” : It will be executed at 12 PM on the last Friday of every month.
You can specify the Cron expression for a scheduled task by using the @Scheduled annotation in the Spring configuration file, as shown below:
@Component
public class MyScheduledTask {
@Scheduled(cron = "0 * * * * *")
public void run() {
// 定时任务的逻辑
}
}
After this configuration, the scheduled task will be executed according to the specified Cron expression.