1、导入maven坐标 spring-context
实际上在项目创建时已近自动引入
2、在启动类添加开启定时任务的注解 @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
@EnableTransactionManagement //开启注解方式的事务管理
@EnableCaching //开启缓存的注解
@EnableScheduling //开启定时任务的注解
@Slf4j
public class SkyApplication {
public static void main(String[] args) {
SpringApplication.run(SkyApplication.class, args);
}
}
3、实现定时任务,每隔5秒打印一次时间
package com.sky.task; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; /*自定义定时任务类*/ @Component @Slf4j public class MyTask { /*定时任务,每隔5秒触发一次*/ @Scheduled(cron = "0/5 * * * * ?") public void executeTask(){ log.info("定时任务开始 {}", new Date()); } }
4、下面直接copy一段项目中的应用场景
业务逻辑: 每个一段时间,查看商品订单支付状态
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 { @Autowired OrderMapper orderMapper; /*处理支付超时订单*/ @Scheduled(cron = "0 * * * * ?") public void processTimeoutOrder(){ log.info("处理支付超时订单:{}", new Date()); //获取15分钟前的时间 LocalDateTime time = LocalDateTime.now().minusMinutes(-15); // 查询15分钟前的待支付状态的订单 List<Orders> orderList = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, time); if(orderList != null && orderList.size() > 0){ for (Orders order : orderList) { order.setStatus(Orders.CANCELLED);//修改订单状态为已取消 order.setCancelReason("订单超时,自动取消");//取消原因 order.setCancelTime(LocalDateTime.now());//取消时间 orderMapper.update(order);//修改当前订单 } } } /** * 处理“派送中”状态的订单 */ @Scheduled(cron = "0 0 1 * * ?") public void processDeliveryOrder(){ log.info("处理派送中订单:{}", new Date()); // 获取当前时间-1小时 LocalDateTime time = LocalDateTime.now().plusMinutes(-60); /*获取一小时前的派送中订单*/ List<Orders> orderList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time); if(orderList != null && orderList.size() > 0){ for (Orders order : orderList) { order.setStatus(Orders.COMPLETED);//修改当前订单为已完成 orderMapper.update(order); } } } }