SpringBoot实现设置动态定时任务的方法详解
一、第一种
1. 引入依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> <optional>true</optional> </dependency> <!-- spring boot 2.3版本后,如果需要使用校验,需手动导入validation包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies>
2. 添加注解
@EnableScheduling @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); System.out.println("(*^▽^*)启动成功!!!(〃'▽'〃)"); } }
3. application.yml
只定义了服务端口:
server: port: 8089
4. task-config.ini
定时任务执行时间配置文件:task-config.ini:
printTime.cron=0/10 * * * * ?
5. 定时任务执行类
package com.gblfy.demo.task; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.util.Date; /** * 定时任务 * @author gblfy */ @Data @Slf4j @Component @PropertySource("classpath:/task-config.ini") public class ScheduleTask implements SchedulingConfigurer { @Value("${printTime.cron}") private String cron; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { // 动态使用cron表达式设置循环间隔 taskRegistrar.addTriggerTask(new Runnable() { @Override public void run() { log.info("Current time: {}", LocalDateTime.now()); } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { // 使用CronTrigger触发器,可动态修改cron表达式来操作循环规则 CronTrigger cronTrigger = new CronTrigger(cron); Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext); return nextExecutionTime; } }); } }
6. 编写一个接口
使得可以通过调用接口动态修改该定时任务的执行时间:
package com.face.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author gblfy */ @Slf4j @RestController @RequestMapping("/test") public class TestController { private final ScheduleTask scheduleTask; @Autowired public TestController(ScheduleTask scheduleTask) { this.scheduleTask = scheduleTask; } //http://localhost:8089/test/updateCron?cron=0/5%20*%20*%20*%20*%20? @GetMapping("/updateCron") public String updateCron(String cron) { log.info("new cron :{}", cron); scheduleTask.setCron(cron); return "ok"; } //http://localhost:8089/test/updateTimer?timer=5000 @GetMapping("/updateTimer") public String updateTimer(Long timer) { log.info("new timer :{}", timer); scheduleTask.setTimer(timer); return "ok"; } }
启动项目,可以看到任务每10秒执行一次: 访问接口,传入请求参数cron表达式,将定时任务修改为15秒执行一次: 可以看到任务变成了15秒执行一次
http://localhost:8089/test/updateCron?cron=0/5 * * * * ?
二、第二种
除了上面的借助cron表达式的方法,还有另一种触发器,区别于CronTrigger触发器,该触发器可随意设置循环间隔时间,不像cron表达式只能定义小于等于间隔59秒。
2.1. 调整定时任务类
package com.face.controller; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.support.CronTrigger; import org.springframework.scheduling.support.PeriodicTrigger; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.util.Date; /** * 定时任务 * @author wl */ @Data @Slf4j @Component @PropertySource("classpath:/task-config.ini") public class ScheduleTask implements SchedulingConfigurer { @Value("${printTime.cron}") private String cron; private Long timer = 10000L; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { // 动态使用cron表达式设置循环间隔 taskRegistrar.addTriggerTask(new Runnable() { @Override public void run() { log.info("Current time: {}", LocalDateTime.now()); } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { // 使用CronTrigger触发器,可动态修改cron表达式来操作循环规则 // CronTrigger cronTrigger = new CronTrigger(cron); // Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext); // 使用不同的触发器,为设置循环时间的关键,区别于CronTrigger触发器,该触发器可随意设置循环间隔时间,单位为毫秒 PeriodicTrigger periodicTrigger = new PeriodicTrigger(timer); Date nextExecutionTime = periodicTrigger.nextExecutionTime(triggerContext); return nextExecutionTime;`在这里插入代码片` } }); } }
2.2. 添加更新方法
@GetMapping("/updateTimer") public String updateTimer(Long timer) { log.info("new timer :{}", timer); scheduleTask.setTimer(timer); return "ok"; }
2.3. 测试
//localhost:8089/test/updateTimer?timer=5000
三、推荐方案
上面有很多弊端,弊端定时任务监控,单机故障等等,建议采用分布式任务调度框架xxl-job
到此这篇关于SpringBoot实现设置动态定时任务的方法详解的文章就介绍到这了,更多相关SpringBoot设置动态定时任务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot如何基于POI-tl和word模板导出庞大的Word文件
这篇文章主要介绍了SpringBoot如何基于POI-tl和word模板导出庞大的Word文件,poi-tl是一个基于Apache POI的Word模板引擎,也是一个免费开源的Java类库2022-08-08Java中实现String.padLeft和String.padRight的示例
本篇文章主要介绍了Java中实现String.padLeft和String.padRight,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-09-09SpringBoot集成netty实现websocket通信功能
Netty是一个高性能、异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端,WebSocket 是一种网络通信协议,相比传统的HTTP协议,本文给大家介绍了SpringBoot集成netty实现websocket通信功能,需要的朋友可以参考下2024-03-03mybatis mybatis-plus-generator+clickhouse自动生成代码案例详解
这篇文章主要介绍了mybatis mybatis-plus-generator+clickhouse自动生成代码案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下2021-08-08Mybatis resultType返回结果为null的问题排查方式
这篇文章主要介绍了Mybatis resultType返回结果为null的问题排查方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-03-03
最新评论