news 2026/3/24 21:08:41

求你别写死了,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/3/15 8:08:38

揭秘Open-AutoGLM高效用法:3个关键技巧让你效率提升200%

第一章&#xff1a;Open-AutoGLM高效用法概述Open-AutoGLM 是一个面向自动化任务的开源大语言模型框架&#xff0c;专为提升自然语言理解与生成效率而设计。其核心优势在于支持多场景零样本迁移、低资源微调以及可插拔式工具链集成&#xff0c;适用于智能客服、文档生成和代码辅…

作者头像 李华
网站建设 2026/3/21 3:07:00

【Open-AutoGLM使用全攻略】:从零入门到实战精通的5大核心步骤

第一章&#xff1a;Open-AutoGLM概述与核心价值Open-AutoGLM 是一个面向通用语言模型自动化推理与生成优化的开源框架&#xff0c;专注于提升大语言模型在复杂任务中的自主规划、工具调用与多步推理能力。该框架通过引入动态思维链&#xff08;Dynamic Chain-of-Thought&#x…

作者头像 李华
网站建设 2026/3/22 1:37:32

GIF动态验证码生成技术实现

GIF动态验证码生成技术实现 在自动化脚本和OCR识别技术日益成熟的今天&#xff0c;传统的静态图片验证码已经难以抵御批量注册、刷票、爬虫等恶意行为。为了应对这一挑战&#xff0c;动态验证码应运而生——其中&#xff0c;GIF格式的多帧动画验证码凭借其时间维度上的视觉变化…

作者头像 李华
网站建设 2026/3/15 9:20:30

创客匠人观察:AI 智能体时代,知识变现的信任重构与价值回归

一、矛盾凸显&#xff1a;AI 效率与信任缺失的知识变现困局“AI 让内容生产效率提升 10 倍&#xff0c;用户付费意愿却下降了”—— 这是 2025 年创始人 IP 面临的核心矛盾。创客匠人调研数据显示&#xff0c;68% 的用户表示 “对 AI 生成的内容缺乏信任”&#xff0c;57% 的用…

作者头像 李华
网站建设 2026/3/15 11:22:58

基于NAM流程的APQP全过程解析与实践

基于NAM流程的APQP全过程解析与实践 在智能电动汽车加速迭代的今天&#xff0c;一款新车型从立项到量产的时间窗口已压缩至24个月以内。面对如此紧张的节奏&#xff0c;任何一次设计返工或供应链断点都可能让项目脱轨。某主机厂曾因一个外饰件供应商未在G6节点前完成DFMEA闭环&…

作者头像 李华