美文网首页
项目中设置定时任务

项目中设置定时任务

作者: 刘小刀tina | 来源:发表于2020-05-12 10:07 被阅读0次

    1. 启动类上添加开启定时任务的注解

    @SpringBootApplication
    @EnableDiscoveryClient
    @EnableFeignClients
    @EnableCommonWeb
    @EnableScheduling //开启定时任务
    public class CampaignServiceApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(CampaignServiceApplication.class, args);
        }
    
    }
    
    

    2.创建定时任务并调用接口

    @Component
    @Slf4j
    public class SchedulOrderJob {
    
        @Autowired
        private OrderService orderService;
    
        @Scheduled(cron = "0 */25 * * * ? ")
        public void run(){
    
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateTime = dateFormat.format(new Date());
            log.info("当前时间为"+dateTime+"开始检查订单时间超过30分钟的自动更新状态");
            orderService.schedulOrderJob();
        }
    
    }
    
    
    

    3. 编写接口代码

    
      /**
         * 定时任务 批量修改超过30分钟待支付订单的状态
         */
        @Override
        public void schedulOrderJob() {
            List<McOrderModel> orders = mcOrderRepository.quertUnpayedOrderDetail();
            if(!orders.isEmpty()){
                orders.forEach(item ->{
                    //数据库查询订单创建时间
                    LocalDateTime createTime = item.getCreateTime();
                    //当前时间
                    LocalDateTime currentTime = LocalDateTime.now();
                    Duration duration = Duration.between(createTime, currentTime);
                    log.info("订单创建时间为:{},当前时间为:{},时差:{}分",createTime,currentTime,duration.toMinutes());
                    if(duration.toMinutes()>=30){
                        //超过30分钟 修改待支付状态为取消并释放库存
                        //log.info("时差满足,需修改订单状态,订单ID为:{}",item.getId());
                        OrderStatusChange orderStatusChange = new OrderStatusChange();
                        orderStatusChange.setId(item.getId());
                        orderStatusChange.setStatus(3);
                        this.statusH5(orderStatusChange);
                        //log.info("ID:{},编号:{}支付状态已修改为取消",item.getId(),item.getOrderNo());
                    }
                });
            }
            log.info("订单时间超过30分钟的状态更新完毕");
    
        }
    
    

    相关文章

      网友评论

          本文标题:项目中设置定时任务

          本文链接:https://www.haomeiwen.com/subject/gupdghtx.html