1.在主启动类上添加EnableScheduling注解表示开启定时器
@SpringBootApplication
@ComponentScan("com.mac")
@MapperScan("com.mac.wikimac.mapper")
@EnableScheduling
public class WikiMacApplication {
2.在方法上写@Scheduled()两种方式执行
@Component
public class TestJob {
private static final Logger LOG = LoggerFactory.getLogger(TestJob.class);
/**
* 固定时间间隔,fixedRate单位毫秒
*/
@Scheduled(fixedRate = 1000)
public void simple() throws InterruptedException {
SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
String dateString = formatter.format(new Date());
Thread.sleep(2000);
LOG.info("每隔5秒钟执行一次: {}", dateString);
}
/**
* 自定义cron表达式跑批
* 只有等上一次执行完成,下一次才会在下一个时间点执行,错过就错过
*/
@Scheduled(cron = "*/1 * * * * ?")
public void cron() throws InterruptedException {
SimpleDateFormat formatter = new SimpleDateFormat("mm:ss SSS");
String dateString = formatter.format(new Date());
Thread.sleep(1500);
LOG.info("每隔1秒钟执行一次: {}", dateString);
}
}
注意事项:在使用定时器使,应尽可能打印出日志信息便于日后运维的排查
在定时方法里打印出定时任务执行时间的耗时
@Scheduled(cron = "5/30 * * * * ?")
public void cron() {
LOG.info("更新电子书下的文档数据开始");
long start = System.currentTimeMillis();
docService.updateEbookInfo();
LOG.info("更新电子书下的文档数据结束,耗时:{}毫秒", System.currentTimeMillis() - start);
}