目录
介绍
Spring Task是Spring框架提供的任务调度工具,可以按照约定的时间,自动执行某个逻辑代码,
定位:定时任务框架
应用场景
短信信息提醒
cron表达式
使用步骤
示例代码
@Component @Slf4j public class OrderTask { @Autowired private OrderMapper orderMapper; //每分钟执行一次.处理订单超时 @Scheduled(cron = "0 * * * * ?") public void processTimeoutOrder() { log.info("OrderTask processTimeoutOrder"); LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15); List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, localDateTime); if (ordersList != null && ordersList.size() > 0) { for (Orders orders : ordersList) { orders.setStatus(Orders.CANCELLED); orders.setCancelTime(LocalDateTime.now()); orders.setCancelReason("订单超时,自动取消"); orderMapper.update(orders); } } } //每天凌晨一点触发一次,处理一直派送中的订单 @Scheduled(cron = "0 0 1 * * ?") public void processDeliveryOrder() { log.info("OrderTask processDeliveryOrder"); LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60); List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, localDateTime); if (ordersList != null && ordersList.size() > 0) { for (Orders orders : ordersList) { orders.setStatus(Orders.COMPLETED); orderMapper.update(orders); } } } }