spring定时器的简单实用

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);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值