How to configure Spring scheduled tasks annotation
In Spring, we can configure scheduled tasks using the @Scheduled annotation. First, add the following configuration to the Spring configuration file.
<task:annotation-driven/>
Next, add the @Scheduled annotation to the method where the scheduled task needs to be executed, and set the scheduled time for the task to run. For example:
@Scheduled(cron = "0 0 0 * * ?") // 每天凌晨执行
public void myTask() {
// 执行定时任务的逻辑
}
The above code represents running the myTask method once every day at midnight.
The @Scheduled annotation has other properties that can be configured, such as:
- fixedRate: executed at a fixed rate, meaning it is triggered at regular intervals, with the unit being milliseconds.
- fixedDelay: This means that the next execution will occur after a fixed delay following the completion of the previous execution, with the delay time measured in milliseconds.
- initialDelay: the initial delay in execution, meaning the task will start after a fixed amount of time has passed, in milliseconds.
- Cron: Configure the timing of scheduled tasks using a cron expression.
For example, running at a fixed frequency:
@Scheduled(fixedRate = 5000) // 每隔 5 秒执行一次
public void myTask() {
// 执行定时任务的逻辑
}
Use fixed delay execution:
@Scheduled(fixedDelay = 5000) // 上一次执行完毕后延迟 5 秒执行下一次
public void myTask() {
// 执行定时任务的逻辑
}
Use initial delay execution:
@Scheduled(initialDelay = 5000, fixedRate = 5000) // 延迟 5 秒后执行第一次,然后每隔 5 秒执行一次
public void myTask() {
// 执行定时任务的逻辑
}