springboot scheduled不执行_Spring Boot集成定时任务

Spring Boot集成定时任务

一、定时任务使用场景

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

二、构建Spring Boot项目

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

org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-starter-test

test

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

在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组件,如图所示:

98364d41baf23848366c40e2f67690b7.png

添加

@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看下定时任务组件执行结果:

1d494b5b2e5c954c7e07e9a73057a338.png

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表示生成一个定时任务实现:

b8e2eec26bb5074d5fb2ffab1048ecd6.png

@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实现定时任务中心,笔者曾经写过定时任务中心代码模块,后面有时间会分享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值