news 2026/1/19 6:24:48

求你别写死了,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进行投诉反馈,一经查实,立即删除!
网站建设 2025/12/26 15:21:32

【Open-AutoGLM数据安全深度剖析】:揭秘AI大模型潜在风险与防护策略

第一章&#xff1a;Open-AutoGLM有没有数据安全问题数据本地化与传输加密机制 Open-AutoGLM 作为开源的自动化代码生成模型&#xff0c;其核心优势之一是支持本地部署。用户可在私有环境中运行模型&#xff0c;避免敏感代码上传至第三方服务器。所有输入输出数据均保留在本地&a…

作者头像 李华
网站建设 2026/1/15 8:04:12

TPAMI‘25 | 首个多轮、开放视角视频问答基准,系统分类9大幻觉任务

基准WildVideo针对多模态模型在视频问答中的「幻觉」问题&#xff0c;首次系统定义了9类幻觉任务&#xff0c;构建了涵盖双重视角、支持中英双语的大规模高质量视频对话数据集&#xff0c;采用多轮开放问答形式&#xff0c;贴近真实交互场景&#xff0c;全面评估模型能力。近年…

作者头像 李华
网站建设 2026/1/11 6:30:33

Java实现多类型图形验证码生成

Java实现多类型图形验证码生成&#xff1a;从零构建安全高效的验证系统 在现代Web应用的安全防线中&#xff0c;图形验证码&#xff08;CAPTCHA&#xff09;始终扮演着关键角色。面对日益猖獗的自动化攻击、暴力破解和恶意爬虫&#xff0c;一个设计得当的验证码机制不仅能有效阻…

作者头像 李华
网站建设 2026/1/18 22:44:53

Windows Server 2016下搭建SQL Server 2012集群

Windows Server 2016下搭建SQL Server 2012集群 在企业级数据库系统中&#xff0c;高可用性是核心诉求之一。尤其在金融、制造、政务等关键业务场景中&#xff0c;任何一次数据库宕机都可能带来不可估量的损失。虽然如今SQL Server已发展到2022版本&#xff0c;但在许多遗留系统…

作者头像 李华
网站建设 2026/1/16 23:45:14

梯度下降法原理与应用详解

梯度下降法&#xff1a;从数学原理到多模态检测实战 你有没有想过&#xff0c;为什么神经网络能“学会”识别图像、检测目标&#xff1f;背后真正的驱动力是什么&#xff1f; 答案不是某个神秘的算法&#xff0c;而是一个看似简单却极其强大的数学思想——沿着最陡的方向下山…

作者头像 李华