spring Task是spring boot中一个简单方便的定时任务
一:
在启动类Application.java中类上面加上@EnableScheduling开启定时任务,也可以启用异步:@EnableAsync
@EnableScheduling // 开启定时任务
@EnableAsync //开启异步
public class Application {
public static void main(String[] args) {
// 程序启动入口
// 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
SpringApplication.run(Application.class,args);
}
}
二:
在controller层需要启用定时任务的方法上面加上@Scheduled注释
//@Scheduled(cron = "0/9 * * * * ? ")//定时9秒钟执行一次
//@Scheduled(cron = "0 5 14 * * ? ")//定时每天14:05执行
@Scheduled(cron = "0 0 9 * * ? ")//定时每天9点执行
public void testTask() throws Exception{
System.out.println("执行定时任务");
timingTaskService.timingTask();
}