您的位置 首页 java

Spring Boot集成定时任务

Spring Boot集成定时任务

一、定时任务使用场景

在项目中有些报表业务需要定时执行,一般在临晨执行或者晚上12点,计算当天的业务汇总,这时就要用到定时任务了。Spring Boot自带了很简单的定时任务功能,可以开启,方便我们实现业务。

二、构建Spring Boot项目

只需要在Maven工程 pom .xml引入以下代码:

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

三、主启动类开启定时任务扫描

在Spring Boot的主启动类CoreSpringStartApplication添加@EnableScheduling

扫描,代码如下:

// 定时任务Scheduled开启注解

// 开启Swagger

@SpringBootApplication

@EnableScheduling

@EnableSwagger2

public class CoreSpringStartApplication {

public static void main(String[] args) {

SpringApplication.run(CoreSpringStartApplication.class, args);

}

}

即可开启定时任务。

四、创建定时任务实现类

新建com.ocai.core.task包,在该包下新建TaskService. java 类,添加@ Component

配置成Spring Bean组件,如图所示:

添加

@Scheduled(cron=”*/6 * * * * ?”)

Cron表达式,表示每隔6秒执行一次:cron=”*/6 * * * * ?”

执行方法代码如下:

private int count=0;
@Scheduled(cron="*/6 * * * * ?")
private void process(){
 System.out.println("this is scheduler task runing "+(count++));
}
 

新建固定

@Scheduled(fixedRate = 6000)
 

表示间隔6000毫秒执行

执行方法代码如下:

@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
 System.out.println("现在时间:" + dateFormat.format(new Date()));
}
 

五、运行主程序Application

运行CoreSpringStartApplication看下定时任务组件执行结果:

this is scheduler task runing 0

现在时间:20:04:54

this is scheduler task runing 1

现在时间:20:05:00

this is scheduler task runing 2

现在时间:20:05:06

this is scheduler task runing 3

现在时间:20:05:12

this is scheduler task runing 4

现在时间:20:05:18

this is scheduler task runing 5

现在时间:20:05:24

this is scheduler task runing 6

=============================================================

表示定时任务已经开启,执行了TaskService中的2个任务。

六、参数说明

TaskService.java中的注解@Scheduled表示生成一个定时任务实现:

@Scheduled可以接受2种定时的设置:

一种是Cron表达式:cron=”*/6 * * * * ?”表示每隔6秒执行一次,Cron表达式还有多种功能,这里不详细举例,可以设置固定的时间点执行等等。

一种是fixedRate = 6000,表示固定间隔6000毫秒执行一次。

fixedRate参数说明:

@Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行

@Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行

@Scheduled(initialDelay=1000, fixedRate=6000) :表示第一次延迟1秒,后面按finxedRate规则每6秒执行一次。

七、总结

Spring Boot通过@EnableScheduling开启自带定时任务功能,可通过Cron表达式以及fixedRate规则执行。关于定时任务还有专门的 Quartz 框架实现。Spring Boot也可以整合Quartz实现定时任务中心,笔者曾经写过定时任务中心代码模块,后面有时间会分享。

文章来源:智云一二三科技

文章标题:Spring Boot集成定时任务

文章地址:https://www.zhihuclub.com/179649.shtml

关于作者: 智云科技

热门文章

网站地图