文章目录
在Spring Boot中整合定时任务可以使用Spring Framework提供的@Scheduled注解,步骤如下:
一、导入依赖
在pom.xml文件中添加下面的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.5.0</version>
</dependency>
二、创建定时任务类
创建一个类,并在类上面添加注解@EnableScheduling,表示开启定时任务的支持。然后在需要执行定时任务的方法上添加@Scheduled注解,设置任务的执行周期。
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("定时任务执行了!");
}
}
三、配置定时任务执行器
在application.properties文件中配置定时任务执行器,这只线程池大小、线程名称前缀等参数:
spring.task.scheduling.pool.size=10
spring.task.scheduling.thread-name-prefix=my-scheduler-
四、项目启动测试
至此,定时任务已经成功完成整合。