Spring Boot 设置动态定时任务,千万别再写死了~

【QUARTZ】springboot+quartz动态配置定时任务 ​ Quartz 定时任务可分为Trigger(触发器)、Job(任务)和Scheduler(调度器),定时任务的逻辑大体为:创建触发器和任务,并将其加入到调度器 ​ 阅读详情

👉 这是一个或许对你有用的社群

🐱 一对一交流/面试小册/简历优化/求职解惑,欢迎加入「芋道快速开发平台」知识星球。下面是星球提供的部分资料: 

007903f22987cdfe97df295c502c10f9.gif

👉这是一个或许对你有用的开源项目

国产 Star 破 10w+ 的开源项目,前端包括管理后台 + 微信小程序,后端支持单体和微服务架构。

功能涵盖 RBAC 权限、SaaS 多租户、数据权限、商城、支付、工作流、大屏报表、微信公众号等等功能:

  • Boot 地址:https://gitee.com/zhijiantianya/ruoyi-vue-pro

  • Cloud 地址:https://gitee.com/zhijiantianya/yudao-cloud

  • 视频教程:https://doc.iocoder.cn

来源:blog.youkuaiyun.com/wl_Honest/

article/details/123654621

3697e87d6a567d239b5645d186236b66.jpeg


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

经过网上搜索学习后,特此记录如何在SpringBoot项目中实现动态定时任务。

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/yudao-cloud

  • 视频教程:https://doc.iocoder.cn/video/

因为只是一个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
public class 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")
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;
            }
        });
    }
}

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

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")
public class TestController {
 
    private final 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秒执行一次:

b7d0a73d2985bd53f8fa9c1227b90fd5.png

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

e59752e8e1039e9a2c250c0776a17f5f.png

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

f4637e2d551acf4a926af8302b99b9d4.png

除了上面的借助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")
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;
            }
        });
    }
}

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

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")
public class TestController {
 
    private final 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";
    }
}

测试结果:

d394defdf224a23e5b35c2f939bee447.png

欢迎加入我的知识星球,全面提升技术能力。

👉 加入方式,“长按”或“扫描”下方二维码噢:

8bd1977e810b7413639e316e63018d2b.png

星球的内容包括:项目实战、面试招聘、源码解析、学习路线。

64867611b96d161eef9d6a02e51b9ae0.png

6409e99084f9ad7edde1152b792716e3.png9ca75380168bf26539f180b8cd1e7929.png679a5583d5eed733391f1072bb662dda.pngd4a8184f3fd874712b96599fe3d69595.png

文章有帮助的话,在看,转发吧。
谢谢支持哟 (*^__^*)
Spring Boot 动态定时任务:实现与应用详解 在现代应用程序中,定时任务是常见且重要的需求。定时任务可以帮助我们定期执行某些操作,如数据备份、日志清理、邮件通知等。在传统的Spring应用中,定时任务通常通过`@Scheduled`注解来实现。然而,这种方式的定时任务是固定的,无法在运行时动态调整。如果应用场景需要根据业务逻辑动态调整任务的执行频率或时间点,那么我们就需要实现动态定时任务。 本文将深入探讨在Spring Boot中如何实现动态定时任务,包括任务的定义、调度、动态更新,以及在实际项目中的应用。我们将通过示例代码和详细解释,使您能够轻松理 阅读详情

相关推荐

springboot定时任务的动态开启关闭

SpringBoot实现定时任务的动态开启关闭,如有疑问联系wx: hsj179540

SpringBoot动态定时任务(完整版)

完整版动态定时任务增删改启动暂停功能样样俱全,话不多说,直接看代码,你们直接CV就可以用!!!

学习学习学习 3万+

全球第一开源云ERP Odoo操作手册 模块安装和界面汉化指南

Odoo 的功能包含在不同的模块中, 刚创建的数据库除 Odoo 的核心模块外, 其它模块并没有被安装到系统中,你可以根据需要安装它们。本节将介绍安装模块和界面汉化的相关知识。

weixin_44793763的博客 2078

SPRING BOOT 动态定时任务

动态定时任务

hudeyong926的专栏 1万+

【脑电绘图教程 2】使用Brainstorm进行脑电处理及源定位

Brainstorm 是一个开源应用程序,支持MEG、EEG、fNIRS、ECoG、深度电极和其他电生理学的数据分析,尤其用于MEG、EEG的源定位。Brainstorm的主要优点是其简单直观的图形界面,不需要进行任何编程,即可上手MEG、EEG分析,此外,它还支持多种数据类型(基本上EEGLab支持的,它都支持),并且具有数据批量处理功能,可以很方便的分析自己的数据。

qq_40735196的博客 1万+

微信内置浏览器抓包全攻略:从ADB配置到Chrome调试(附常见问题解决)

本文提供了一套完整的微信内置浏览器抓包与调试解决方案。从ADB工具的深度配置与稳定性连接开始,详细讲解了如何开启X5内核调试开关,并利用Chrome DevTools建立远程连接。文章重点剖析了Network面板进行网络请求抓取、性能分析和问题定位的实战技巧,并附带了设备连接失败、无网络请求等常见问题的排查指南,帮助开发者高效解决微信H5页面调试难题。

gitlab7runner的博客 547

SpringBoot 设置动态定时任务,千万别再写死了~

点击上方“芋道源码”,选择“设为星标”管她前浪,还是后浪?能浪的浪,才是好浪!每天 10:33更新文章,每天掉亿点点头发...源码精品专栏原创 | Java 2021超神之路,很肝~中文详细注释的开源项目RPC 框架 Dubbo 源码解析网络应用框架 Netty 源码解析消息中间件 RocketMQ 源码解析数据库中间件 Sharding-JDBC 和 MyCAT 源码解析作业调度中间件 E...

芋艿V 360

Openwork 入门指南:开源 AI 桌面助手快速上手

Openwork是一款开源的AI桌面代理工具,提供类似Claude Cowork的免费替代方案。它支持本地运行,确保隐私安全,并能高效处理文件整理、文档读写等任务。支持多种AI模型,通过MIT许可完全免费。安装简单,仅需运行命令行或下载桌面版,需配置API Key后即可使用。操作直观,支持多步骤规划和权限控制,适合自动化重复工作。目前主要支持macOS,未来将扩展至Windows/Linux。建议从简单任务入手,逐步掌握这一高效的数字助手工具。

3806
上一篇: Java 中的 Stream 可以替代 for 循环吗?
下一篇: EXP 一款 Java 插件化热插拔框架
公众号-芋道源码
博客等级 码龄10年 1640粉丝 377原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值