Spring Task实现苍穹外卖订单超时和派送中的业务功能
·
一、SpringTask概念
Spring Task是spring框架提供的任务调度工具,可以按照约定的时间自动执行某个代码逻辑
作用就是定时执行某段java代码。
二、cron表达式

三、maven坐标依赖
spring Task的maven坐标为spring-context,因为spring-boot-starter中包含了spring-context坐标,根据依赖的传递性,所以这里只需引入springboot starter的依赖即可。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

第四步:在启动类添加@EnableScheduling注解
package com.sky;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@Slf4j
@EnableScheduling//开启定时任务功能
public class SkyApplication {
public static void main(String[] args) {
SpringApplication.run(SkyApplication.class, args);
log.info("server started");
}
}
第五步:实现超时订单和派送订单
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 * * * * ?")
//@Scheduled(cron = "1/5 * * * * ?")
public void processTimeoutOrder(){
log.info("处理超时订单:{}", LocalDateTime.now());
//查询15分钟之前未支付订单
LocalDateTime time=LocalDateTime.now().plusMinutes(-15);
List<Orders> ordersList=orderMapper.getByStatusAndOrderTimeLT(time,Orders.PENDING_PAYMENT);
if(ordersList!=null&&ordersList.size()>0){
//遍历超时的订单,并将状态设置成取消
for(Orders order:ordersList){
order.setStatus(Orders.CANCELLED);
order.setCancelReason("订单超时,自动取消");
order.setCancelTime(LocalDateTime.now());
orderMapper.update(order);
}
}
}
/**
* 处理一直处于派送中的订单状态
*/
@Scheduled(cron="0 0 1 * * ?")
//@Scheduled(cron = "0/5 * * * * ?")
public void processDeliveryOrder(){//每天凌晨一点触发一次
log.info("处理派送中的订单:{}",LocalDateTime.now());
//查询15分钟之前未支付订单
LocalDateTime time=LocalDateTime.now().plusMinutes(-60);
List<Orders> ordersList=orderMapper.getByStatusAndOrderTimeLT(time,Orders.DELIVERY_IN_PROGRESS);
if(ordersList!=null&&ordersList.size()>0){
//遍历超时的订单,并将状态设置成取消
for(Orders order:ordersList){
order.setStatus(Orders.COMPLETED);
order.setDeliveryTime(LocalDateTime.now());
orderMapper.update(order);
}
}
}
}
更多推荐



所有评论(0)