如何在Springboot中设置定时任务,自动取消超时订单
我在网上找了很久,很多都是redis和rabbitmq去解决的,但我这个项目本身不大,不值得去专门加一个rabbitmq,于是就用了springboot自带的定时任务,又更好的方法欢迎评论指出来。
1、pom.xml中导入必要的依赖:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <!-- SpringBoot 核心组件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
2、在springboot启动类上 启动类里面使用@EnableScheduling 注解开启功能,自动扫描
@SpringBootApplication(scanBasePackages = { "org.ahtl.wash.db", "org.ahtl.wash.core", "org" + ".ahtl.wash.admin"}) @MapperScan("org.ahtl.wash.db.dao") @EnableTransactionManagement @EnableScheduling //开启定时任务 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
3、写一个job
类上要写@Component,方法上要写@Scheduled cron语句自行百度,有很多,我的是每隔30分钟执行一次
@Component public class TimerJob { private final Log logger = LogFactory.getLog(TimerJob.class); @Resource private WashCardOrderExportService washCardOrderExportService; @Resource private WashOrderExportService washOrderExportService; @Resource private WashRechargeOrderExportService washRechargeOrderExportService; /** * 修改超时未充值次卡订单,余额充值订单 * <p> * <p> */ @Scheduled(cron = "0 0/30 * * * ?") public void invalidCard() { // 取消大于30min的订单 //修改超时未充值次卡订单 washCardOrderExportService.CardUpdate(); washRechargeOrderExportService.RechargeUpdate(); }
4、取消的逻辑代码自己写完直接运行项目即可。