使用定时任务的弊端
在使用定时任务(每小时检查)关闭超时未支付订单场景下:
- 会有时间差,程序不严谨
10:30 下单,在11:00 检查不足一小时,12:00 检查,并关闭订单,超时1小时30分钟
- 不支持集群
单机没毛病,使用集群后,就会有多个定时任务
解决方案:只是用一台计算机节点,单独用来运行所有的定时任务
- 会对数据库全表搜索,极其影响数据库性能:select * from order where orderStatus = 10;
定时任务,仅仅适用于小型轻量级项目、传统项目
目前主流解决方案——消息队列:
使用延时任务(队列)
10:12分下单,未付款状态 —-> 11:12 检查,如果还是未付款状态,则直接关闭订单
代码实现
package com.shiers.config;
import com.shiers.service.OrderService;
import com.shiers.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* Demo class
*
* @author shierS
* @date 2021/6/5
*/
@Component
public class OrderJob {
@Autowired
private OrderService orderService;
// 👇 crom表达式
@Scheduled(cron = "0 0 0/1 * * ?")
public void autoCloseOrder(){
//关闭超时订单
orderService.closeOrder();
System.out.println("执行定时任务:当前时间为:"
+ DateUtil.getCurrentDateString(DateUtil.DATETIME_PATTERN));
}
}
注解开启定时任务
在启动类上添加注解@EnableScheduling
// 扫描mybatis通用的mapper所在的包
@MapperScan(basePackages = "com.shiers.mapper")
@SpringBootApplication
// 扫描所有包 以及相关组件包
@ComponentScan(basePackages = {"com.shiers","org.n3r.idworker"})
// 👇开启定时任务👇
@EnableScheduling 👈
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}