Article directory
2. Create a scheduled task class
3. Configure the scheduled task executor
To integrate scheduled tasks in Spring Boot, you can use the @Scheduled annotation provided by Spring Framework. The steps are as follows:
1. Import dependencies
Add the following dependencies in the pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.5.0</version>
</dependency>
2. Create a scheduled task class
Create a class and add the annotation @EnableScheduling to the class to indicate support for enabling scheduled tasks. Then add the @Scheduled annotation on the method that needs to execute the scheduled task to set the execution cycle of the task.
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@EnableScheduling
public class MyTask {
@Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
public void myTask() {
System.out.println("定时任务执行了!");
}
}
3. Configure the scheduled task executor
Configure the scheduled task executor in the application.properties file, including the thread pool size, thread name prefix and other parameters:
spring.task.scheduling.pool.size=10
spring.task.scheduling.thread-name-prefix=my-scheduler-
4. Project startup testing
At this point, the scheduled tasks have been successfully integrated.