6.01 定时任务,关闭超时订单

步骤1:创建定时任务类

import com.imooc.service.OrderService;
import com.imooc.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class OrderJob {
    @Autowired
    private OrderService orderService;

    /**
     * 使用定时任务关闭超期未支付订单,会存在的弊端:
     * 1. 会有时间差,程序不严谨
     *      10:39下单,11:00检查不足1小时,12:00检查,超过1小时多余39分钟
     * 2. 不支持集群
     *      单机没毛病,使用集群后,就会有多个定时任务
     *      解决方案:只使用一台计算机节点,单独用来运行所有的定时任务
     * 3. 会对数据库全表搜索,及其影响数据库性能:select * from order where orderStatus = 10;
     * 定时任务,仅仅只适用于小型轻量级项目,传统项目
     *
     * 后续课程会涉及到消息队列:MQ-> RabbitMQ, RocketMQ, Kafka, ZeroMQ...
     *      延时任务(队列)
     *      10:12分下单的,未付款(10)状态,11:12分检查,如果当前状态还是10,则直接关闭订单即可
     */

    @Scheduled(cron = "0/3 * * * * ?")
    public void autoCloseOrder() {
        orderService.closeOrder();
        System.out.println("执行定时任务,当前时间为:"
                + DateUtil.getCurrentDateString(DateUtil.DATETIME_PATTERN));
    }

}

步骤2:开启定时任务

@EnableScheduling // 开启定时任务

步骤3:超时订单改成关闭状态
1.OrderService接口中

/**
 * 关闭超时未支付订单
 */
public void closeOrder();

2.OrderService实现类中

@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) {
			// 超过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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java之书

会持续更新实用好的文章谢谢关注

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值