项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息,Spring为我们提供了异步执行任务调度的方式,提供了两个接口,TaskExecutor接口和TaskScheduler接口,以及两个注解:@EnableScheduling和@Scheduled
创建一个ScheduledService
@Service
public class ScheduledService {
@Scheduled(cron = "0/2 * * * * ?")
public void hello(){
System.out.println("hello.....");
}
}
写完定时任务之后,我们需要在主程序上增加@EnableScheduling 开启定时任务功能
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class Springboot05Application {
public static void main(String[] args) {
SpringApplication.run(Springboot05Application.class, args);
}
}