启动类上添加@EnableScheduling ,开启Springboot自带的定时任务功能
@SpringBootApplication
@EnableScheduling
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication .class, args);
}
}
创建一个定时任务,每天8点执行一次
@Component
public class TestScheduling {
private static int i = 0;
@Scheduled(cron = "0 0 8 * * ?")//每天凌晨8点执行
public void test(){
System.out.println("this is "+ (i++) + "times!");
}
}
在application.properties中添加定时任务的开关配置
## 定时任务基础配置
scheduling:
enabled: true #定时任务开关 默认开启
修改定时任务的默认注解开关
@Component
//默认条件注解是开启的,现在采用配置文件的变量来手动控制定时任务是否执行 设置关闭
@ConditionalO