SoFunction
Updated on 2025-04-05

spring @Scheduled timed task annotation and summary of precautions

@ScheduledAnnotation 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@ScheduledThe 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@ScheduledAnnotation 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 configuredThreadPoolTaskSchedulerCome for@ScheduledTasks 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@ScheduledThe 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@AsyncAnnotations and@EnableAsyncAnnotation to make each@ScheduledTasks 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@Asyncannotation:

@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@ScheduledThe 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@AsyncAnnotations 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@ScheduledAnnotated 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 * *

2. zone

  • meaning: Specifies the time zone to parse cron expressions.
  • typeString, the default value is an empty string, indicating the default time zone of the server.
  • ExampleAsia/Shanghai

3. fixedRate

  • meaning: Specifies that the task is executed at a fixed time interval in milliseconds.
  • typelong, 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

4fixedRateString

  • meaning:andfixedRateSimilar, but using string types, placeholders are supported.
  • typeString, 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.
  • typelong, 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:andfixedDelaySimilar, but using string types, placeholders are supported.

typeString, 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.
  • typelong, 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:andinitialDelaySimilar, but using string types, placeholders are supported.
  • typeString, 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.
  • fixedRateandfixedDelay: 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!