SpringBoot's @Scheduled annotation usage
@Scheduled is the core annotation used in Spring Framework to implement timing tasks, which can easily configure methods to execute at specific times or cycles.
The following is a detailed analysis:
1. Enable timing tasks
In Spring Boot, you need to add the @EnableScheduling annotation to the configuration class to enable timed task support:
@Configuration @EnableScheduling public class AppConfig { }
2. Basic usage
Add directly to the method@Scheduled
Annotation and configure execution rules:
@Component public class ScheduledTasks { // Fixed delay (interval after task ends) @Scheduled(fixedDelay = 5000) public void taskWithFixedDelay() { // Execute every 5 seconds (time starts after the task is completed) } // Fixed rate (the interval at which task starts) @Scheduled(fixedRate = 3000) public void taskWithFixedRate() { // Execute every 3 seconds (time starts after the task starts) } // Initial delay (wait time before first execution) @Scheduled(initialDelay = 10000, fixedRate = 5000) public void taskWithInitialDelay() { // Delay for 10 seconds for the first time, and then execute every 5 seconds. } // Cron expression (complex time rules) @Scheduled(cron = "0 0 12 * * ?") public void taskWithCronExpression() { // Perform at 12 noon every day } }
3. Detailed explanation of parameters
(1) fixedDelay
- Function: Fixed delay time (unit: milliseconds) after the task is completed.
- Example: @Scheduled(fixedDelay = 5000) means that you wait 5 seconds after the task is over and then execute the next time.
- Applicable scenarios: You need to ensure that the previous task is completed and then executed again.
(2) fixedRate
- Function: Fixed time interval (unit: milliseconds) at the start of the task.
- Example: @Scheduled(fixedRate = 3000) means that it is executed every 3 seconds (regardless of whether the previous task is completed or not).
- Note: If the task execution time exceeds the interval, it may cause tasks to overlap (need to be configured in combination with thread pool).
(3) initialDelay
- Function: The initial delay time (unit: milliseconds) before the first task is executed.
- Example: @Scheduled(initialDelay = 10000, fixedRate = 5000) means that the first delay is performed after 10 seconds, and then every 5 seconds.
(4) cron
- Function: Define complex scheduling rules through Cron expressions.
- Cron expression format: seconds minute time day month anniversary year (optional)
- Common examples:
- 0 0 10 * * ?: Performed at 10 am every day.
- 0 0/5 14 * * ?: Starting at 2 pm every day, it is executed every 5 minutes.
- 0 15 10 ? * MON-FRI: Performed from Monday to Friday at 10:15 am.
- Online Tool: The Cron Expression Generator is recommended.
4. Thread pool configuration
By default, timing tasks are executed using a single thread. If the task takes a long time, you need to configure the thread pool to avoid blocking:
@Configuration public class SchedulerConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { (taskExecutor()); } @Bean(destroyMethod = "shutdown") public Executor taskExecutor() { return (10); // Customize the number of threads } }
5. Notes
1. Avoid long-term blockage: If the task execution time exceeds the scheduling interval, logical design or thread pool should be configured reasonably.
2. Distributed environment issues: In a cluster, timing tasks may be repeatedly executed by multiple instances. Solution:
- Use distributed locks (such as Redis or ZooKeeper).
- Control task execution through database unique identification.
3. Dynamic adjustment: The default @Scheduled parameter does not support dynamic modification. For dynamic scheduling, you can combine ScheduledTaskRegistrar or use the Quartz framework.
6. FAQ
Q1: What is the difference between ? and * in Cron expressions?
-
*
Indicates any value (such as:*
In the "Day" field, it means every day). -
?
Mutex conditions for "Day" and "Week" fields (avoid conflicts).
Q2: How to avoid repeated tasks execution?
- Standalone environment: Ensure task idempotence.
- Distributed environment: Use distributed locks or database unique constraints.
Q3: How to debug timing tasks?
- Turn on Spring's debug log: =DEBUG
Summarize
@Scheduled is a convenient tool for implementing timing tasks in Spring. It can meet most scheduling needs by flexibly configuring fixedDelay, fixedRate, or cron expressions.
In complex scenarios such as dynamic tasks or distributed environments, more advanced features can be achieved in combination with Quartz or other distributed scheduling frameworks.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.