开始

完善定时任务,把一个未付款的超时订单改为订单改为交易关闭。
找到对应的service

image.png

image.png

  1. /**
  2. * 关闭超时 未支付的订单
  3. */
  4. public void closeOrder();

方法的实现
image.png

@Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public OrderStatus queryOrderStatusInfo(String orderId) {

        return orderStatusMapper.selectByPrimaryKey(orderId);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void closeOrder() {
        // 查询所有未支付的订单,判断时间是否超过(1天) 超时则关闭交易
        OrderStatus queryOrder=new OrderStatus();
        queryOrder.setOrderStatus(OrderStatusEnum.WAIT_PAY.type);
        List<OrderStatus> list = orderStatusMapper.select(queryOrder);

    }

查询所有等待付款的订单列表
image.png
获取订单创建时间和当前时间的对比
image.png

 @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void closeOrder() {
        // 查询所有未支付的订单,判断时间是否超过(1天) 超时则关闭交易
        OrderStatus queryOrder=new OrderStatus();
        queryOrder.setOrderStatus(OrderStatusEnum.WAIT_PAY.type);
        List<OrderStatus> list = orderStatusMapper.select(queryOrder);
        for (OrderStatus os :
                list) {
            // 获得订单创建时间
            Date createdTime = os.getCreatedTime();
            // 和当前事件进行对比
            int days = DateUtil.daysBetween(createdTime, new Date());
            if(days>1){

            }
        }
    }

关闭订单方法,单独封装
image.png

   @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void closeOrder() {
        // 查询所有未支付的订单,判断时间是否超过(1天) 超时则关闭交易
        OrderStatus queryOrder=new OrderStatus();
        queryOrder.setOrderStatus(OrderStatusEnum.WAIT_PAY.type);
        List<OrderStatus> list = orderStatusMapper.select(queryOrder);
        for (OrderStatus os :
                list) {
            // 获得订单创建时间
            Date createdTime = os.getCreatedTime();
            // 和当前事件进行对比
            int days = DateUtil.daysBetween(createdTime, new Date());
            if(days>1){
                doCloseOrder(os.getOrderId());
            }
        }
    }
    @Transactional(propagation = Propagation.REQUIRED)
    void doCloseOrder(String orderId) {
        OrderStatus close=new OrderStatus();
        close.setOrderId(orderId);
        close.setOrderStatus(OrderStatusEnum.CLOSE.type);
        close.setCloseTime(new Date());
        orderStatusMapper.updateByPrimaryKeySelective(close);
    }

注入orderService,定时任务关闭订单

image.png
maven install
image.png

测试

当前数据库内有很多的订单是待支付的状态
image.png
重新启动服务,定时任务已经执行。
image.png

数据库内数据刷新。10状态的订单已经全部改成了50 关闭。
image.png
每个小时。
image.png
改成一个小时

0 0 0/1 * * ?

image.png
定时任务有弊端,下一节聊。

结束