千峰商城-springboot项目搭建-86-订单超时取消-定时任务查询超时未支付订单
订单超时取消:当用户成功提交订单之后在规定时间内如果没有完成支付,则将订单关闭,还原库存。
实现订单的超时取消通常有两种解决方案:
1.使用定时任务(循环扫描)(quartz)
2.延时队列(MQ)
一、流程分析

二、实现
1.在service中的pom.xml中添加定时任务依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
2.在api子工程启动类中添加启动定时任务的注解@EnableScheduling
@EnableScheduling @SpringBootApplication @MapperScan("com.qfedu.fmmall.dao") public class ApiApplication { public static void main(String[] args) { SpringApplication.run(ApiApplication.class, args); } }
3.在service包下新建job包

job包下新建OrderTimeoutCheckJob类。
OrderTimeoutCheckJob:
@Component public class OrderTimeoutCheckJob { @Autowired private OrdersMapper ordersMapper; @Scheduled(cron = "0/5 * * * * ?") public void checkAndCloseOrder(){ //1.查询超过30分钟,订单状态依然为待支付状态的订单 Example example = new Example(Orders.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("status","1"); Date time = new Date(System.currentTimeMillis() - 30*60*1000); criteria.andLessThan("createTime",time); List<Orders> orders = ordersMapper.selectByExample(example); } }
4.测试:
@Autowired private OrdersMapper ordersMapper; @Test public void test(){ Example example = new Example(Orders.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("status","1"); Date time = new Date(System.currentTimeMillis() - 30*60*1000); criteria.andLessThan("createTime",time); List<Orders> orders = ordersMapper.selectByExample(example);
for (int i = 0; i < orders.size(); i++) {
System.out.println(orders.get(i).getOrderId()+"\t"
+orders.get(i).getCreateTime()+"\t"+orders.get(i).getStatus());
}
}

测试成功!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤