启动类上添加@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

本文介绍了如何在SpringBoot应用中配置定时任务,通过@EnableScheduling开启定时任务功能,并展示了如何创建一个每天8点执行的定时任务。此外,还详细讲解了如何在application.properties中配置任务开关以及通过@Scheduled注解的fixedDelay、fixedRate和cron参数控制任务执行方式。同时,文章提到了如何使用条件注解控制任务是否执行,以及cron表达式的常见用法。
最低0.47元/天 解锁文章
9708

被折叠的 条评论
为什么被折叠?



