SoFunction
Updated on 2025-04-12

SpringBoot project uses @Scheduled annotation to implement timing tasks

SpringBoot project [Use @Scheduled annotation to implement timing tasks]

There are currently three main ways to create timing tasks using SpringBoot:

1. Based on annotation (@Scheduled)

- The easiest and most direct
2. Interface-based (SchedulingConfigurer)

- Suitable for reading a specified time from the database in actual use to dynamically execute timing tasks
3. Set multi-threaded timing tasks based on annotations

1. Based on annotation (@Scheduled)

1.1 Use of @Scheduled annotations and @EnableScheduling annotations

Based on the annotation @Scheduled is a single thread by default. When multiple tasks are enabled, the execution of the task will be affected by the execution time of the previous task.

@EnableScheduling annotation: Use on the configuration class to enable support for scheduled tasks (on the class).

@Scheduled annotation: To declare this is a task, including cron, fixDelay, fixRate and other types (in terms of method, you need to enable the support of planned tasks first).

【Example】In SpringBoot project, use @Scheduled annotation and @EnableScheduling annotation to implement timing tasks.

(1) Turn on the timing task

SpringBoot project adds the @EnableScheduling annotation to the project startup class to enable timed task management.

import ;
import ;
import ;
@SpringBootApplication
@EnableScheduling //Open the timing taskpublic class ScheduledDemoApplication
{
    public static void main(String[] args)
    {
        (, args);
    }
}

(2) Create a timed task

Create a timed task and use the @Scheduled annotation.

package ;
import ;
import ;
import ;
import ;
/**
  * Use of timing tasks
  * @author pan_junbiao
  **/
@Component
public class Task
{
    @Scheduled(cron="0/5 * *  * * ? ")   //Execute every 5 seconds    public void execute(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //Set date format        ("Welcome to pan_junbiao's blog" + (new Date()));
    }
}

1.2 @Scheduled Annotation Parameter Explanation

@ScheduledAnnotations have multiple parameters, and the following are several commonly used parameters:

cron

Receives a cron expression. A cron expression consists of six or seven domains, and the common format is as follows:

css
Copy Edit
[seconds] [minutes] [hours] [days] [months] [weeks] [years]

Serial number illustrate Is it required Allowed values Allowed wildcards
1 Second yes 0-59 , - * /
2 point yes 0-59 , - * /
3 Hour yes 0-23 , - * /
4 day yes 1-31 , - * ? / L W
5 moon yes 1-12 or JAN-DEC , - * /
6 week yes 1-7 or SUN-SAT , - * ? / L #
7 Year no Empty or 1970-2099 , - * /

Wildcard description:

? means no value is specified. The scenario used is that you do not need to care about the value of this field currently set. For example: To trigger an operation on the 10th of each month, but don’t care about the weekly day, so the field that needs to be set to "?" is set to "?" specifically to 0 0 0 10 * ?

-Denotes interval. For example, setting "10-12" on the hour means that 10, 11, 12 points will be triggered.

, means specifying multiple values, such as setting "MON,WED,FRI" on the weekly field means triggering on Monday, Wednesday and Friday

/ for incremental triggering. If setting "5/15" on the second, it means that starting from 5 seconds, triggering every 15 seconds (5,20,35,50). Set the '1/3' on the month field to start the first day of the month and trigger every three days.

L means the final meaning. On the day field setting, it indicates the last day of the month (based on the current month, if it is February, it will also be based on whether it is Runnian [leap]). On the week field, it indicates Saturday, which is equivalent to "7" or "SAT". If a number is preceded by "L", it means the last one of the data. For example, setting a format like "6L" in the weekly field means "the last Friday of the month"

W indicates the closest working day to the specified date (Monday to Friday). For example, set "15W" in the day field to indicate the closest working day to the 15th of each month. (Note, only specific numbers can be set before "W", intervals are not allowed"-")

Common examples:

Timed task expressions describe
0 0 12 * * ? Triggered at 12 o'clock every day
0 15 10 ? * * Triggered at 10:15 every day
0 15 10 * * ? Triggered at 10:15 every day
0 15 10 * * ? * Triggered at 10:15 every day
0 15 10 * * ? 2025 Triggered at 10:15 every day in 2025
0 * 14 * * ? Every afternoon, each minute triggered from 2:00 to 2:59
0 0/5 14 * * ? Every afternoon from 2:00 to 2:59 (starting at the hour and triggering every 5 minutes)
0 0/5 14,18 * * ? Every afternoon from 2:00 to 2:59 (starting at the hour, triggering every 5 minutes) every afternoon from 18:00 to 18:59 (starting at the hour, triggering every 5 minutes)
0 0-5 14 * * ? Every afternoon, every minute triggered from 2:05 to 2:05
0 10,44 14 ? 3 WED March triggers at 2:10 and 2:44 on Wednesday afternoon
0 15 10 ? * MON-FRI Triggered from Monday to Friday at 10:15 am every morning
0 15 10 15 * ? Triggered at 10:15 am on the 15th of each month
0 15 10 L * ? Triggered at 10:15 on the last day of each month
0 15 10 ? * 6L Triggered at 10:15 on Friday of the last week of each month
0 15 10 ? * 6L 2022-2025 Triggered at 10:15 on Friday of the last week of each month from 2022 to 2025
0 15 10 ? * 6#3 The third week of each month starts triggering
0 0 12 1/5 * ? Trigger every 5 days starting at the first noon of each month
0 11 11 11 11 ? Every year, November 11th, triggered at 11:11 (Single's Day)

Other commonly used

  • fixedDelay: How many milliseconds will be executed after the last task is completed.
  • fixedRate: How many milliseconds will be executed after the last task begins.
  • initialDelay: How many milliseconds will be delayed for the first time before execution.

2. Dynamic timing tasks: based on interface (SchedulingConfigurer)

2.1 Create a database table

Create a cron table in the MySQL database to store cron expressions for timing tasks:

DROP TABLE IF EXISTS cron;
CREATE TABLE cron (
    cron_id VARCHAR(30) NOT NULL PRIMARY KEY,
    cron VARCHAR(30) NOT NULL
);
INSERT INTO cron VALUES ('1', '0/5 * * * * ?');

2.2 Add MyBatis dependency

existAdd the JDBC dependencies for MyBatis and MySQL:

<!-- MyBatisandSpringBootIntegrated dependency -->
<dependency>
    <groupId></groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
<!-- MySQLofJDBCDatabase Driver -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.20</version>
</dependency>

2.3 Create a timed task configuration class

package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
  * Dynamic timing task configuration class
  * @author pan_junbiao
  **/
@Configuration
@EnableScheduling
public class DynamicScheduleConfigurer implements SchedulingConfigurer {
    @Mapper
    public interface CronMapper {
        @Select("select cron from cron limit 1")
        public String getCron();
    }
    @Autowired
    CronMapper cronMapper;
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        (
                () -> ("Welcome to pan_junbiao's blog: " + ().toLocalTime()),
                triggerContext -> {
                    String cron = ();
                    if ((cron)) {
                        // Error handling                    }
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}

3. Set multi-threaded timing tasks based on annotations

pass@AsyncAnnotation enables multi-threaded timing tasks to solve the problem of mutual influence when multiple tasks are executed.

Create multi-threaded timed tasks

package ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
  * Set multi-threaded timing tasks based on annotations
  * @author pan_junbiao
  */
@Component
@EnableScheduling   // Turn on timing tasks@EnableAsync        // Turn on multi-threadingpublic class MultithreadScheduleTask {
    @Async
    @Scheduled(fixedDelay = 1000)  // 1 second interval    public void first() throws InterruptedException {
        ("The first timed task begins: " + ().toLocalTime() + "\r\nThread: " + ().getName());
        (1000 * 10);
    }
    @Async
    @Scheduled(fixedDelay = 2000)
    public void second() {
        ("The second timed task begins: " + ().toLocalTime() + "\r\nThread: " + ().getName());
    }
}

Notice

because@ScheduledThe default is single-threaded mode. When multiple timing tasks are enabled, the execution order of tasks will be affected by the execution time of the previous task. pass@AsyncAnnotation, we can solve this problem and enable multiple timing tasks to be executed in parallel.

Through the above three methods, Spring Boot provides flexible timing task support, and you can choose the appropriate implementation method according to project needs.

This is the article about the implementation of timing tasks using @Scheduled annotation for SpringBoot projects. For more related SpringBoot @Scheduled timing tasks, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!