@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class OrderCancelTask {
Logger logger = LoggerFactory.getLogger(OrderCancelTask.class);
@Value("${web.order-create-time-key}")
private String ORDERS_CREATE_TIME_KEY;
@Autowired
private OrdersInfoService ordersInfoService;
//3.添加定时任务
//@Scheduled(cron = "0/5 * * * * ?")
//或直接指定时间间隔,例如:5秒
@Scheduled(fixedRate=5000)
public void configureTasks() {
logger.info("自动取消超时未支付订单任务开始...");
List<String> cancelOrder = new ArrayList<>();
List<String> orderNos = (List<String>) RedisClient.get(ORDERS_CREATE_TIME_KEY);
if (orderNos != null && orderNos.size()>0){
for (String orderNo : orderNos){
String no = orderNo.substring(0,orderNo.indexOf("-"));
String time = orderNo.substring(orderNo.indexOf("-")+1);
Long orderTime = Long.parseLong(time);
Long now = new Date().getTime();
if (now - orderTime > 1000){
logger.info("自动取消超时未支付订单: " + no + ",订单时间:" +time);
ordersInfoService.orderTimeOut(no);
cancelOrder.add(orderNo);
}
}
orderNos.removeAll(cancelOrder);
}
RedisClient.set(ORDERS_CREATE_TIME_KEY,orderNos,-1);
}
}