1// 1. 在主启动类上加上支持定时任务的注解 2@EnableScheduling 3public class Application { 4 5 6// 2. 编写定时任务 7@Component 8public class OrderJob { 9 10 @Autowired 11 private OrderService orderService; 12 13 /** 14 * 使用定时任务关闭超期未支付订单,会存在的弊端: 15 * 1. 会有时间差,程序不严谨 16 * 10:39下单,11:00检查不足1小时,12:00检查,超过1小时多余39分钟 17 * 2. 不支持集群 18 * 单机没毛病,使用集群后,就会有多个定时任务 19 * 解决方案:只使用一台计算机节点,单独用来运行所有的定时任务 20 * 3. 会对数据库全表搜索,及其影响数据库性能:select * from order where orderStatus = 10; 21 * 定时任务,仅仅只适用于小型轻量级项目,传统项目 22 * 23 * 后续课程会涉及到消息队列:MQ-> RabbitMQ, RocketMQ, Kafka, ZeroMQ... 24 * 延时任务(队列) 25 * 10:12分下单的,未付款(10)状态,11:12分检查,如果当前状态还是10,则直接关闭订单即可 26 */ 27 28 // @Scheduled(cron = "0/3 * * * * ?") 29 // @Scheduled(cron = "0 0 0/1 * * ?") 30 public void autoCloseOrder() { 31 orderService.closeOrder(); 32 System.out.println("执行定时任务,当前时间为:" 33 + DateUtil.getCurrentDateString(DateUtil.DATETIME_PATTERN)); 34 } 35 36} 37 38 39 @Transactional(propagation = Propagation.REQUIRED) 40 @Override 41 public void closeOrder() { 42 43 // 查询所有未付款订单,判断时间是否超时(1天),超时则关闭交易 44 OrderStatus queryOrder = new OrderStatus(); 45 queryOrder.setOrderStatus(OrderStatusEnum.WAIT_PAY.type); 46 List<OrderStatus> list = orderStatusMapper.select(queryOrder); 47 for (OrderStatus os : list) { 48 // 获得订单创建时间 49 Date createdTime = os.getCreatedTime(); 50 // 和当前时间进行对比 51 int days = DateUtil.daysBetween(createdTime, new Date()); 52 if (days >= 1) { 53 // 超过1天,关闭订单 54 doCloseOrder(os.getOrderId()); 55 } 56 } 57} 58 59@Transactional(propagation = Propagation.REQUIRED) 60void doCloseOrder(String orderId) { 61 OrderStatus close = new OrderStatus(); 62 close.setOrderId(orderId); 63 close.setOrderStatus(OrderStatusEnum.CLOSE.type); 64 close.setCloseTime(new Date()); 65 orderStatusMapper.updateByPrimaryKeySelective(close); 66}
4、定时任务关闭超时未支付的订单
Wesley13
2021-10-11
1151 0 0
点赞
收藏
评论区
加载中...