当前位置: 首页 > news >正文

求你别写死了,SpringBoot 写死的定时任务也能动态设置,爽~

之前写过文章记录怎么在SpringBoot项目中简单使用定时任务,不过由于要借助cron表达式且都提前定义好放在配置文件里,不能在项目运行中动态修改任务执行时间,实在不太灵活。

经过一番研究之后,特此记录如何在SpringBoot项目中实现动态定时任务。

因为只是一个demo,所以只引入了需要的依赖:

<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>

启动类:

package com.wl.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; /** * @author wl */ @EnableScheduling @SpringBootApplication publicclass DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); System.out.println("(*^▽^*)启动成功!!!(〃'▽'〃)"); } }

配置文件application.yml,只定义了服务端口:

server: port: 8089

定时任务执行时间配置文件:task-config.ini:

printTime.cron=0/10 * * * * ?

定时任务执行类:

package com.wl.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 wl */ @Data @Slf4j @Component @PropertySource("classpath:/task-config.ini") publicclass 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; } }); } }

编写一个接口,使得可以通过调用接口动态修改该定时任务的执行时间:

package com.wl.demo.controller; import com.wl.demo.task.ScheduleTask; 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 wl */ @Slf4j @RestController @RequestMapping("/test") publicclass TestController { privatefinal ScheduleTask scheduleTask; @Autowired public TestController(ScheduleTask scheduleTask) { this.scheduleTask = scheduleTask; } @GetMapping("/updateCron") public String updateCron(String cron) { log.info("new cron :{}", cron); scheduleTask.setCron(cron); return"ok"; } }

启动项目,可以看到任务每10秒执行一次:

访问接口,传入请求参数cron表达式,将定时任务修改为15秒执行一次:

可以看到任务变成了15秒执行一次

除了上面的借助cron表达式的方法,还有另一种触发器,区别于CronTrigger触发器,该触发器可随意设置循环间隔时间,不像cron表达式只能定义小于等于间隔59秒。

package com.wl.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.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") publicclass 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; } }); } }

增加一个修改时间的接口:

package com.wl.demo.controller; import com.wl.demo.task.ScheduleTask; 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 wl */ @Slf4j @RestController @RequestMapping("/test") publicclass TestController { privatefinal ScheduleTask scheduleTask; @Autowired public TestController(ScheduleTask scheduleTask) { this.scheduleTask = scheduleTask; } @GetMapping("/updateCron") public String updateCron(String cron) { log.info("new cron :{}", cron); scheduleTask.setCron(cron); return"ok"; } @GetMapping("/updateTimer") public String updateTimer(Long timer) { log.info("new timer :{}", timer); scheduleTask.setTimer(timer); return"ok"; } }

测试结果:

http://www.jsqmd.com/news/144147/

相关文章:

  • Open-AutoGLM源码实战应用,5个真实场景教你打造专属智能Agent
  • 专科生必看!9个高效降AIGC工具推荐,轻松应对AI检测
  • 2025年最受欢迎的苗木批发基地盘点,无刺枸骨球/红叶石楠/丝棉木/金森女贞/国槐/樱花/金叶复叶槭/苗木苗木批发基地批发商推荐排行榜单 - 品牌推荐师
  • 探索SGLang + Qwen2-7B-Instruct 在_Atlas 800T 的推理调优
  • 2026重庆儿童学习障碍干预去哪家医院好?这份口碑与效果双优的选择攻略请收好 - 品牌2026
  • 【大模型开发必看】Open-AutoGLM源码剖析:3步实现智能推理链自动生成
  • Open-AutoGLM开源地址找不到?资深AI工程师亲授3种精准定位方法
  • 手把手教你开启智谱清言沉思模式,这6个参数设置必须精准到位
  • Numpy入门详细教程:核心用法一网打尽
  • C语言读取文本中的图像数据转为BMP
  • python小区物业管理系统_2oma5
  • 学长亲荐9个AI论文软件,研究生搞定毕业论文不求人!
  • 2025年高性价比的互联网推广企业推荐,互联网推广老牌公司全解析 - mypinpai
  • 全球钢丝绳市场:中国领跑下的结构性变革与新兴机遇
  • 2025年度环保无动力雨水净化系统十大品牌排行榜 - 工业品网
  • Exchange 2007 属性参考指南
  • 三步搭建“钉钉待办推送” (curl版)
  • 揭秘智谱Open-AutoGLM核心架构:5步实现本地高效部署与调优
  • python智能停车场车位租赁管理系统vue
  • Yarn Lockfile 分析与依赖管理
  • 常见文件格式转国产ofd案例,支持pdf、word、txt;
  • 激光打孔机选购指南:研发实力、维护成本与企业选择 - myqiye
  • Open-AutoGLM使用避坑指南(9大常见错误及解决方案)
  • 【Php期末大作业带数据库】Php+MySQL电商商品展示平台设计与实现、电子购物商城系统(附源码)
  • Open-AutoGLM部署成功率提升80%,这7个关键参数设置你调对了吗
  • DC综合与静态时序分析优化实战
  • 【JPCS出版 | EI检索】第七届新材料与清洁能源国际学术会议(ICAMCE 2026)
  • 《智能体入门课》第一课|从 ChatGPT 到智能体:为什么现在人人都在谈「Agent」
  • 2025年口碑好的美甲培训学校推荐,专业美甲课程与就业支持全解析 - 工业推荐榜
  • Ryuko-NEHT Reloaded! MAME 0.116 Hack合集