@Scheduled
Annotation is an annotated timing task scheduling tool provided by Spring to simplify the implementation of timing tasks. Its default behavior isSingle threaded execution, that is, tasks are executed in the same thread by default. If the task throws an exception or executes it too long, it may affect the scheduling of subsequent tasks.
In Spring, use@Scheduled
The default is the multiple timing tasks defined by the annotation.Single thread execution in sequenceof. This means that if multiple timing tasks are triggered to be executed at the same time, they will be executed sequentially in the order of task registration, rather than in parallel.
Default behavior
-
Single threaded execution: Spring's
@Scheduled
Annotation uses a single thread scheduler by default (SimpleScheduledExecutor
), so multiple tasks are executed serially. - Task blocking: If a task executes too long, it will block the execution of subsequent tasks.
How to implement parallel execution
If multiple timing tasks need to be executed in parallel, it can be implemented in the following ways:
Method 1: Configure the multithreaded scheduler
Can be configuredThreadPoolTaskScheduler
Come for@Scheduled
Tasks provide a thread pool, allowing multiple tasks to be executed in parallel.
Sample code:
@Configuration public class ScheduleConfig { @Bean public ThreadPoolTaskScheduler taskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); (5); // Set the thread pool size ("my-scheduled-task-"); return scheduler; } }
exist@Scheduled
The custom scheduler is specified in the annotation:
@Scheduled(fixedRate = 5000, scheduler = "taskScheduler") public void task1() { // Task content}
Method 2: Use @Async annotation
Can be combined@Async
Annotations and@EnableAsync
Annotation to make each@Scheduled
Tasks are executed asynchronously in independent threads.
Sample code:
@Configuration @EnableAsync public class AsyncConfig { @Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); (5); // Set the thread pool size return scheduler; } }
Add on task method@Async
annotation:
@Async @Scheduled(fixedRate = 5000) public void task1() { // Task content}
Method 3: Set the thread pool size through configuration file
In Spring Boot, you can set it directly through the configuration fileProperties to increase the thread pool size.
Sample configuration:
=5
Summarize
-
Default behavior:
@Scheduled
The default annotation is to execute it in sequence by a single thread. -
Parallel execution: It can be configured by configuring a multi-threaded scheduler or using
@Async
Annotations implement parallel execution. -
Recommended method: Configure multithreaded scheduler (
ThreadPoolTaskScheduler
) is the most commonly used method and is suitable for most scenarios.
Through the above methods, it is easy to implement the parallel execution of multiple timing tasks!
The following is@Scheduled
Annotated parameters and detailed descriptions:
1. cron
- meaning: Specify a cron expression to define the execution time of the task.
- Format:cron expression consists of 6 or 7 fields, representing seconds, minutes, hours, days, months, weeks (and years).
-
Example:
- Execute every 5 seconds:
0/5 * * * * *
- Perform once every day at 23:
0 0 23 * * *
- Perform once every month at 1 a.m.:
0 0 1 1 * *
- Execute every 5 seconds:
2. zone
- meaning: Specifies the time zone to parse cron expressions.
-
type:
String
, the default value is an empty string, indicating the default time zone of the server. -
Example:
Asia/Shanghai
3. fixedRate
- meaning: Specifies that the task is executed at a fixed time interval in milliseconds.
-
type:
long
, the default value is-1
, means that the fixed rate is not used. -
Example:
@Scheduled(fixedRate = 5000)
Indicates that it is executed every 5 seconds
4. fixedRateString
-
meaning:and
fixedRate
Similar, but using string types, placeholders are supported. -
type:
String
, the default value is an empty string. -
Example:
@Scheduled(fixedRateString = "5000")
Indicates that it is executed every 5 seconds
5. fixedDelay
- meaning: Specifies that the task will be executed again after a fixed time interval after the last execution is completed, in milliseconds.
-
type:
long
, the default value is-1
, means that no fixed delay is used. -
Example:
@Scheduled(fixedDelay = 5000)
It means that after the last task is executed, wait for 5 seconds to execute the next time.
6. fixedDelayString
meaning:andfixedDelay
Similar, but using string types, placeholders are supported.
type:String
, the default value is an empty string.
Example:@Scheduled(fixedDelayString = "5000")
It means that after the last task is executed, wait for 5 seconds to execute the next time.
7. initialDelay
- meaning: Specifies the delay time before the task is first executed, in milliseconds.
-
type:
long
, the default value is-1
, means that the initial delay is not used. -
Example:
@Scheduled(initialDelay = 5000, fixedRate = 10000)
Indicates that the first delay is executed after 5 seconds, and then every 10 seconds
8. initialDelayString
-
meaning:and
initialDelay
Similar, but using string types, placeholders are supported. -
type:
String
, the default value is an empty string. -
Example:
@Scheduled(initialDelayString = "5000", fixedRateString = "10000")
Indicates that the first delay is executed after 5 seconds, and then every 10 seconds
9. CRON_DISABLED
- meaning: A special cron expression value that disables timing tasks.
-
value:
"-"
, when the cron expression is set to"-"
When the task is disabled
Summarize
-
cron
: Suitable for complex timing task scheduling, such as execution at a specific point in time. -
fixedRate
andfixedDelay
: Suitable for simple timing task scheduling, such as execution at fixed times. -
initialDelay
: Used to control the first execution time of a task. -
zone
: Used to specify a time zone to ensure that the task is executed in the correct time zone.
By rationally using these parameters, you can flexibly configure the execution plan of timed tasks to meet various business needs.
This is the article about how to use spring @Scheduled timed task annotation and precautions. For more related spring @Scheduled timed task annotation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!