我们在开发Java Web项目时,经常会用到定时任务帮我们周期性地处理一些业务,比如定期扣款、定时发货等,实现定时任务的方式有好几种,而SpringBoot已经帮我们实现了其中的一种,并且使用起来非常简单,也无需额外地导包,然后各种xml配置。下面,来和潘老师一起看一下我们应该如何使用SpringBoot来实现定时任务。

1、创建简单的SpringBoot Web项目

使用SpringBoot创建一个Java Web项目,这个学过SpringBoot的同学应该都没有任何问题,我这里只创建了一个名为timer的简单web项目作为演示,只引入了spring boot devtoolsspring web (starter)模块(仅引入spring web (starter)模块也可):

其中pom.xml中的依赖如下:

 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> 

如果想搭建SSM的项目环境可以参考:

2、使用@EnableScheduling注解开启定时任务

在启动类TimerApplication上面加上@EnableScheduling注解即可开启定时任务,我这里的启动类代码如下:

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

3、实现定时任务类

  • 要在任务的类上写@Component注解
  • 要在任务方法上写@Scheduled注解

1)我在此新建com.panziye.timer.task包,在包中新建MyTask任务类,并加上@Component将任务类作为组件交给Spring管理,Spring Boot容器就会根据任务类方法上@Scheduled中配置的时间,来定时执行每个方法。我这里先写几个案例代码如下:

 package com.panziye.timer.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; @Component public class MyTask { //表示每隔3秒执行一次 @Scheduled(fixedRate = 3000) public void fixedRateTask() { System.out.println("fixedRateTask 每隔3秒===" + new Date()); } //表示方法执行完成后5秒执行一次 @Scheduled(fixedDelay = 5*1000) public void fixedDelayTask() throws InterruptedException { System.out.println("fixedDelayTask 该任务结束后5秒=====" + new Date()); } //使用cron表达式来表示每小时50分30秒执行一次 @Scheduled(cron = "30 50 * * * ?") public void cronTask() { System.out.println("cronTask 每小时50分30秒========"+new Date()); } } 

2)我们运行TimerApplication发现任务都定时执行,结果如下图所示:

关于cron表达式具体的内容需要参考潘老师的个人博客: