iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >SpringBoot如何设置动态定时任务
  • 469
分享到

SpringBoot如何设置动态定时任务

2023-07-02 08:07:13 469人浏览 薄情痞子
摘要

这篇文章主要介绍了SpringBoot如何设置动态定时任务的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇springBoot如何设置动态定时任务文章都会有所收获,下面我们一起来看看吧。之前写过文章记录怎么在Sp

这篇文章主要介绍了SpringBoot如何设置动态定时任务的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇springBoot如何设置动态定时任务文章都会有所收获,下面我们一起来看看吧。

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

因为只是一个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; @EnableScheduling@SpringBootApplicationpublic 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; @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; @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秒执行一次: 

SpringBoot如何设置动态定时任务

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

SpringBoot如何设置动态定时任务

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

SpringBoot如何设置动态定时任务

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

测试结果:

SpringBoot如何设置动态定时任务

关于“SpringBoot如何设置动态定时任务”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“SpringBoot如何设置动态定时任务”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程网精选频道。

--结束END--

本文标题: SpringBoot如何设置动态定时任务

本文链接: https://www.lsjlt.com/news/340630.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 如何在 Golang 中替换正则表达式匹配的文本?
    在 go 中,可使用 regexp.replaceall 函数替换符合正则表达式的文本,该函数需要三个参数:待替换字符串、匹配模式和替换文本。例如,将字符串中 "fox" 替换为 "do...
    99+
    2024-05-14
    golang 正则表达式
  • 如何在 Golang 中测试随机数生成器的准确性?
    在 go 中测试随机数生成器准确性的步骤包括:生成大量随机数并计算每个范围内的出现次数,以确保均匀分布。针对指定均值和标准差计算每个范围内的出现次数,以确保正态分布。 如何在 Gola...
    99+
    2024-05-14
    golang 随机数
  • 面向对象设计原则在C++中的体现
    c++++ 体现了 oop 原则,包括:封装:使用类将数据和方法封装在对象中。继承:允许派生类从基类继承数据和行为。多态:允许对象的行为根据其类型而改变,通过虚函数实现。 面向对象设计...
    99+
    2024-05-14
    c++ 面向对象
  • c语言怎么区分小数和整数
    c 语言区分小数和整数的方法有:数据类型不同:小数类型(float、double)包含小数点,整数类型(int)不包含。printf() 函数中使用不同格式化字符串:小数用 %f,整数用...
    99+
    2024-05-14
    c语言
  • 设计模式在C++ 中的可复用性和可扩展性
    在 c++++ 中,设计模式通过提供经过验证的解决方案来提高可复用性和可扩展性。可复用性允许重复使用代码,例如 factory method 模式,它支持创建不同的产品而不影响具体类。可...
    99+
    2024-05-14
    c++ 设计模式 高可扩展性
  • C++语法中函数模板的灵活运用
    C++ 语法中函数模板的灵活运用 函数模板是 C++ 中的一项强大功能,允许您创建可用于不同数据类型的一组代码。这可以提高代码的可重用性,并使您能够编写更通用、更可维护的代码。 语法 ...
    99+
    2024-05-14
    c++语法 函数模板 c++
  • c语言怎么计算字符串长度和宽度
    在 c 语言中,计算字符串长度和宽度的函数分别为:strlen() 函数用于计算字符串长度,不包括终止符 '\0'。strwidth() 函数用于计算字符串在终端中的宽度,返回显示像素数...
    99+
    2024-05-14
    c语言
  • 如何用 Golang 正则匹配多个单词或字符串?
    golang 正则表达式使用管道符 | 来匹配多个单词或字符串,将各个选项作为逻辑 or 表达式分隔开来。例如:匹配 "fox" 或 "dog":fox|dog匹配 "quick"、"b...
    99+
    2024-05-14
    golang 正则 python
  • c语言怎么跳出多层循环
    在 c 语言中,可以使用嵌套的 break 语句跳出多层循环。对于每个要跳出的循环层,都需要一个单独的 break 语句。例如:使用一个 break 语句跳出内层循环再使用一个 brea...
    99+
    2024-05-14
    c语言
  • c语言怎么注释成中文
    c语言中文注释提供两种方式:行内注释(以"//"开头)和块注释(以"/"开头并以"/"结尾)。最佳实践包括:使用简明扼要的语言,在函数和类开头处添加块注释,在关键部分添加行内注释,保持注...
    99+
    2024-05-14
    c语言
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作