news 2026/4/22 14:15:34

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
求你别写死了,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"; } }

测试结果:

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/23 11:58:17

Java 面试题:百度前200页都在这里了

这里汇总整理了网络上的Java面试题&#xff0c;百度搜索“Java面试题”前200页。基本概念 操作系统中 heap 和 stack 的区别什么是基于注解的切面实现什么是 对象/关系 映射集成模块什么是 Java 的反射机制什么是 ACIDBS与CS的联系与区别Cookie 和 Session的区别fail-fast 与 …

作者头像 李华
网站建设 2026/4/19 2:00:32

UG固定轴与可变轴曲面轮廓铣加工详解

UG固定轴与可变轴曲面轮廓铣加工详解 在模具制造、航空航天零部件以及复杂自由曲面零件的数控加工中&#xff0c;如何高效且精准地完成表面精修&#xff0c;一直是工程师面临的核心挑战。尤其是在五轴联动技术日益普及的今天&#xff0c;UG NX&#xff08;Unigraphics NX&…

作者头像 李华
网站建设 2026/4/23 11:34:50

Yarn Lock文件解析与依赖管理

Yarn Lock文件解析与依赖管理 在现代前端和全栈项目中&#xff0c;依赖管理早已不再是简单的 npm install 就能一劳永逸的事。随着项目规模扩大、协作人数增多&#xff0c;如何确保团队成员、CI/CD 环境、生产部署之间的依赖完全一致&#xff0c;成为保障构建可重现性的关键。…

作者头像 李华
网站建设 2026/4/18 7:42:19

阅文45位大神作家真容曝光,天蚕土豆最吸睛

阅文45位大神作家真容曝光&#xff0c;天蚕土豆最吸睛 最近在整理网络文学行业资料时&#xff0c;我偶然翻到阅文集团发布的一组视频素材——整整45位签约大神作家首次集体露脸&#xff01;这些平日只存在于笔名背后的“文字魔法师”&#xff0c;终于从幕后走到台前。更让我兴…

作者头像 李华
网站建设 2026/4/23 13:17:31

Hepcidin-25

1. 基本信息英文名称&#xff1a;Hepcidin - 25 (Human)中文名称&#xff1a;人源铁调素 - 25氨基酸序列&#xff1a;天冬氨酸 - 苏氨酸 - 组氨酸 - 苯丙氨酸 - 脯氨酸 - 异亮氨酸 - 半胱氨酸 - 异亮氨酸 - 苯丙氨酸 - 半胱氨酸 - 半胱氨酸 - 甘氨酸 - 半胱氨酸 - 半胱氨酸 - 组…

作者头像 李华
网站建设 2026/4/17 3:13:30

矩阵论的奠基与现代科技应用

腾讯混元OCR&#xff1a;当矩阵论遇见智能视觉 在伦敦的一间律师事务所里&#xff0c;19世纪的数学家阿瑟凯莱曾用钢笔在纸上写下几行公式——那是一组关于“矩形阵列”的运算法则。他或许未曾想到&#xff0c;这份名为《矩阵论的研究报告》的手稿&#xff0c;会在一百多年后成…

作者头像 李华