启动类上添加@EnableScheduling ,开启Springboot自带的定时任务功能
@SpringBootApplication
@EnableScheduling
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication .class, args);
}
}
创建一个定时任务,间隔5秒执行一次
@Component
public class TestScheduling {
private static int i = 0;
@Scheduled(fixedDelay=5*1000)
public void test(){
System.out.println("this is "+ (i++) + "times!");
}
}
执行结果
在application.properties中添加定时任务的开关配置
## 定时任务基础配置
scheduling:
enabled: true #定时任务开关
修改定时任务的默认注解开关
@Component
//默认条件注解是开启的,现在采用配置文件的变量来手动控制定时任务是否执行
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class TestScheduling {
private static int i = 0;
@Scheduled(fixedDelay=5*1000)
public void test(){
System.out.println("this is "+ (i++) + " times!");
}
}
更多推荐
SpringBoot+Schedule 定时任务的配置开关
发布评论