定时任务
1.在启动类上添加注解@EnableScheduling
@SpringBootApplication
@EnableScheduling//开启定时任务
public class StatisticsApplication {
public static void main(String[] args) {
SpringApplication.run(StatisticsApplication.class,args);
}
}
2创建定时任务类
在这个类里面使用cron表达式,设置规则,设置什么时候去执行
@Component
public class ScheduledTask {
// "0/5 * * * * ?"每隔五秒执行一次这个方法
@Scheduled(cron = "0/5 * * * * ?")
public void task1(){
Date date = new Date();
System.out.println(date+"task1执行了");
}
}
在需要定时执行的方法前加上注解 @Scheduled(),其中利用corn表达式(七子表达式)来制定规则,由于springboot最后一位默认是当年,因此只有6位数,且写七位springboot会报错
在线生成cron表达式:https://cron.qqe2.com/
举例:每天1点进行执行代码,下面会生成相对于corn表达式