注解@EnableScheduling开启任务调度、定时任务

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

一、启动类开启注解

@EnableScheduling //开启任务调度 定时任务

二、新建定时任务OrderTask类

在定时任务方法上写上注解@Scheduled,并且设置规则。

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.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单的方法
     */
    @Scheduled(cron = "0 * * * * ? ") //每分钟触发一次
    public void processTimeOutOrder(){
        log.info("处理超时订单:{}", LocalDateTime.now());
        // select * from orders where status = ? and order_time < (当前时间-15分钟)
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> orderList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, localDateTime);
        if(orderList!=null && orderList.size()>0){
            orderList.forEach(order->{
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });

        }
    }

    /**
     * 一直处于派送中,修改状态 已完成
     */
    @Scheduled(cron = "0 0 1 * * ?") //每月每日凌晨一点执行
    public void processDeliveryOrder(){
        log.info("定时处理派送中的订单:");
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> orderList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        if(orderList!=null && orderList.size()>0){
            orderList.forEach(order->{
                order.setStatus(Orders.COMPLETED);
//                order.setDeliveryTime(LocalDateTime.now());
//                order.setRemark("订单处理派送中的订单,已完成");
                orderMapper.update(order);
            });

        }
    }
}

备注:具体规则根据业务需求进行调整,不用死记!不用死记!不用死!

可以参考在线Cron表达式生成器在线Cron表达式生成器

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值