使用定时任务的弊端

在使用定时任务(每小时检查)关闭超时未支付订单场景下:

  1. 会有时间差,程序不严谨

10:30 下单,在11:00 检查不足一小时,12:00 检查,并关闭订单,超时1小时30分钟

  1. 不支持集群

单机没毛病,使用集群后,就会有多个定时任务
解决方案:只是用一台计算机节点,单独用来运行所有的定时任务

  1. 会对数据库全表搜索,极其影响数据库性能:select * from order where orderStatus = 10;

定时任务,仅仅适用于小型轻量级项目、传统项目

目前主流解决方案——消息队列:
使用延时任务(队列)
10:12分下单,未付款状态 —-> 11:12 检查,如果还是未付款状态,则直接关闭订单

代码实现

  1. package com.shiers.config;
  2. import com.shiers.service.OrderService;
  3. import com.shiers.utils.DateUtil;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.scheduling.annotation.Scheduled;
  6. import org.springframework.stereotype.Component;
  7. /**
  8. * Demo class
  9. *
  10. * @author shierS
  11. * @date 2021/6/5
  12. */
  13. @Component
  14. public class OrderJob {
  15. @Autowired
  16. private OrderService orderService;
  17. // 👇 crom表达式
  18. @Scheduled(cron = "0 0 0/1 * * ?")
  19. public void autoCloseOrder(){
  20. //关闭超时订单
  21. orderService.closeOrder();
  22. System.out.println("执行定时任务:当前时间为:"
  23. + DateUtil.getCurrentDateString(DateUtil.DATETIME_PATTERN));
  24. }
  25. }

注解开启定时任务

在启动类上添加注解@EnableScheduling

  1. // 扫描mybatis通用的mapper所在的包
  2. @MapperScan(basePackages = "com.shiers.mapper")
  3. @SpringBootApplication
  4. // 扫描所有包 以及相关组件包
  5. @ComponentScan(basePackages = {"com.shiers","org.n3r.idworker"})
  6. // 👇开启定时任务👇
  7. @EnableScheduling 👈
  8. public class Application {
  9. public static void main(String[] args) {
  10. SpringApplication.run(Application.class,args);
  11. }
  12. }

cron表达式生成网站

https://cron.qqe2.com/