章
目
录
我们在开发Java Web项目时,经常会用到定时任务帮我们周期性地处理一些业务,比如定期扣款、定时发货等,实现定时任务的方式有好几种,而SpringBoot已经帮我们实现了其中的一种,并且使用起来非常简单,也无需额外地导包,然后各种xml配置。下面,来和潘老师一起看一下我们应该如何使用SpringBoot来实现定时任务。
1、创建简单的SpringBoot Web项目
使用SpringBoot创建一个Java Web项目,这个学过SpringBoot的同学应该都没有任何问题,我这里只创建了一个名为timer的简单web项目作为演示,只引入了spring boot devtools和spring 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的项目环境可以参考:
之前给大家在博文中讲过如何通过eclipse快速搭建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发现任务都定时执行,结果如下图所示:

1.
@Scheduled注解属性fixedRate和fixedDelay比较说明:它们单位都是毫秒(可以是通过表达式计算出的结果),我在这里分别设置为3秒和5秒。
它们的区别就是:
fixedRate不论该定时任务执行完需要花费了多少时间,它每隔设置的时长就触发再次执行。而fixedDelay是当该定时任务执行完毕后再等待设置的时长再次执行。因此我们需要根据实际业务不同,采取不同的方式。
2. @Scheduled注解也可以使用cron表达式来设置时间,灵活度更高,比如我们可以设置每个星期三的凌晨1点指定任务,或者每个月的最后一天的凌晨12点50分0秒执行定时任务等等。
关于cron表达式具体的内容需要参考潘老师的个人博客:
当我们学习java框架Spring定时任务时,我们经常会需要设置定时任务运行时间,比如每个小时运行1次,或每周 […]







