项目中常常会用到定时器,用来执行耗时操作。
springboot整合
使用起来很简单
1.主函数上增加开启定时器的注解
@EnableScheduling
2.新建一个定时任务类Task
@Component
public class Task {
// @Scheduled(cron = "*/5 * * ? * *")
/**
* fixedRate上一个调用开始后再次调用的延时(不用等待上一次调用完成)
*/
// @Scheduled(fixedRate = 1 * 1000)
/**
* 等到方法执行完成后延迟配置的时间再次执行该方法
*/
@Scheduled(fixedDelay = 1 * 1000)
public void Task() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis());
}
}
使用@Component
注解声明好,方法上直接@Scheduled(cron = “/5 * ? * *”),写好cron表达式即可。