OrderTimeoutCancelTask.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package com.etotem.cfc.task;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.etotem.cfc.entity.ProductOrder;
  4. import com.etotem.cfc.mapper.ProductOrderMapper;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.scheduling.annotation.Scheduled;
  9. import org.springframework.stereotype.Component;
  10. import javax.annotation.Resource;
  11. import java.util.Calendar;
  12. import java.util.Date;
  13. import java.util.List;
  14. import com.etotem.cfc.util.SortUtil;
  15. import com.etotem.cfc.config.DatabaseInitializer;
  16. @Component
  17. public class OrderTimeoutCancelTask {
  18. private static final Logger log = LoggerFactory.getLogger(OrderTimeoutCancelTask.class);
  19. @Resource
  20. private ProductOrderMapper orderMapper;
  21. @Value("${shop.order.payment-timeout-minutes:30}")
  22. private int paymentTimeoutMinutes;
  23. @Scheduled(fixedRate = 60000) // 每分钟执行一次
  24. public void cancelTimeoutOrders() {
  25. if (!DatabaseInitializer.isMigrationsComplete()) {
  26. log.info("数据库迁移尚未完成,跳过本轮订单超时检查");
  27. return;
  28. }
  29. // 计算超时时间点
  30. Calendar cal = Calendar.getInstance();
  31. cal.add(Calendar.MINUTE, -paymentTimeoutMinutes);
  32. Date timeoutTime = cal.getTime();
  33. // 查找超时未支付的订单
  34. LambdaQueryWrapper<ProductOrder> wrapper = new LambdaQueryWrapper<ProductOrder>()
  35. .eq(ProductOrder::getStatus, "pending")
  36. .lt(ProductOrder::getCreatedAt, timeoutTime);
  37. SortUtil.applySort(wrapper);
  38. List<ProductOrder> timeoutOrders = orderMapper.selectList(wrapper);
  39. if (timeoutOrders.isEmpty()) {
  40. return;
  41. }
  42. // 取消每个超时订单
  43. for (ProductOrder order : timeoutOrders) {
  44. order.setStatus("cancelled");
  45. order.setUpdatedAt(new Date());
  46. orderMapper.updateById(order);
  47. log.info("订单 {} 超时未支付,已自动取消", order.getOrderNo());
  48. }
  49. log.info("本次共取消 {} 个超时订单", timeoutOrders.size());
  50. }
  51. }