一、概述
(1)SpringBoot定时任务通常来讲就是给程序设定一个时间让它在指定时间运行。
(2)要开启定时任务,只需在SpringBoot中做几个简单的配置
二、案例一:基于注解@Scheduled(静态的)
基于注解@Scheduled默认为单线程,开启多个任务时,任务的执行时机会受上一个任务执行时间的影响。
【1】创建一个SpringBoot程序,这里我使用的是SpringBoot 2.3.3版本
【2】在SpringBoot的启动类上配置@EnableScheduling开启定时任务
@SpringBootApplication
@EnableScheduling // 开启定时任务
public class Demo02Application {
public static void main(String[] args) {
SpringApplication.run(Demo02Application.class, args);
}
}
【3】创建一个Spring的配置类,写一个定时方法
@Configuration //标记配置类
public class StaticScheduleTask {
//添加定时任务
@Scheduled(cron = "0/3 * * * * ?")
//或直接指定时间间隔,例如:每3秒执行一次
//@Scheduled(fixedRate=3000)
private void configureTasks() {
System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
}
}
【4】控制台打印
这里可以看到,每隔三秒,定时任务就会执行一次,但是我们要改变执行时间时,需要重启程序。
三、案例二:基于接口SchedulingConfigurer(动态的)
【1】pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--添加MySql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mys