定时器的实现有Java Timer、Quartz和spring自带的Scheduled,spring的比较简单,只需要通过注解配置就可以实现
1.创建定时任务
@Component
public class ScheduledTask {
// 每30秒钟执行一次
@Scheduled(cron = "0/30 * * * * ?")
public void sayHello() {
System.out.println("-------------- scheduled task start----------");
}
}
2.Application中添加注解@EnableScheduling
@ComponentScan(value = "com")
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application .class, args);
}
}