| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- package com.etotem.cfc.task;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.etotem.cfc.entity.ProductOrder;
- import com.etotem.cfc.mapper.ProductOrderMapper;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Component;
- import javax.annotation.Resource;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.List;
- import com.etotem.cfc.util.SortUtil;
- import com.etotem.cfc.config.DatabaseInitializer;
- @Component
- public class OrderTimeoutCancelTask {
- private static final Logger log = LoggerFactory.getLogger(OrderTimeoutCancelTask.class);
- @Resource
- private ProductOrderMapper orderMapper;
- @Value("${shop.order.payment-timeout-minutes:30}")
- private int paymentTimeoutMinutes;
- @Scheduled(fixedRate = 60000) // 每分钟执行一次
- public void cancelTimeoutOrders() {
- if (!DatabaseInitializer.isMigrationsComplete()) {
- log.info("数据库迁移尚未完成,跳过本轮订单超时检查");
- return;
- }
- // 计算超时时间点
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.MINUTE, -paymentTimeoutMinutes);
- Date timeoutTime = cal.getTime();
- // 查找超时未支付的订单
- LambdaQueryWrapper<ProductOrder> wrapper = new LambdaQueryWrapper<ProductOrder>()
- .eq(ProductOrder::getStatus, "pending")
- .lt(ProductOrder::getCreatedAt, timeoutTime);
- SortUtil.applySort(wrapper);
- List<ProductOrder> timeoutOrders = orderMapper.selectList(wrapper);
- if (timeoutOrders.isEmpty()) {
- return;
- }
- // 取消每个超时订单
- for (ProductOrder order : timeoutOrders) {
- order.setStatus("cancelled");
- order.setUpdatedAt(new Date());
- orderMapper.updateById(order);
- log.info("订单 {} 超时未支付,已自动取消", order.getOrderNo());
- }
- log.info("本次共取消 {} 个超时订单", timeoutOrders.size());
- }
- }
|