1.Spring Task 任务调度工具
2.cron表达式
@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@EnableCaching//开启springboot2.x的redis缓存
@EnableScheduling//开启定时任务
@Slf4j
public class SkyApplication {public static void main(String[] args) {SpringApplication.run(SkyApplication.class, args);log.info("server started");}
}
①maven坐标Task---Spring context
②启动类加@EnableScheduling
③定时任务加载类@Compent
@Scheduled(cron='0/5 * * * * ?')
LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
查询订单状态为未支付且下单时间超过15分钟的订单(select * from order where status=#{status} and order_time < #{time}),
把订单状态改为取消,设置取消原因,时间,更新到订单中
④运行程序会自动检查是否符合条件修改
package com.sky.task;import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;/*** 自定义定时任务,实现订单状态定时处理*/
@Component
@Slf4j
public class OrderTask {@Autowiredprivate OrderMapper orderMapper;/*** 处理超时订单,每秒*/@Scheduled(cron="0 * * * * ?")public void processTimeOutOrder() {log.info("处理支付超市的订单:{}",new Date());//1.下单时间LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//2.查询当前订单,订单状态是为未支付,且时间小于15min
// select * from orders where status=1 and order_time < 当前时间-15min;List<Orders> list=orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT,time);if(list!=null&&list.size()>0){//3.遍历集合,修改订单状态为已取消for (Orders orders : list) {//1.修改订单状态为已取消orders.setStatus(Orders.CANCELLED);//2.设置取消原因orders.setCancelReason("订单未支付超时,自动取消");//3.设置取消时间orders.setCancelTime(LocalDateTime.now());orderMapper.update(orders);}}}/*** 处理派送中的订单,每天*/@Scheduled(cron="0 0 1 * * ?")public void processDeliveryOrder() {log.info("处理派送中的订单:{}",new Date());LocalDateTime time = LocalDateTime.now().plusDays(-1);List<Orders> list=orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS,time);if(list!=null&&list.size()>0){for (Orders orders : list) {//1.修改订单状态为已完成orders.setStatus(Orders.COMPLETED);//2.设置完成时间orders.setDeliveryTime(LocalDateTime.now());orderMapper.update(orders);}}}}