• Java实现---动态修改定时任务的执行时间


    实现的效果

    通过接口调用,在不重启服务的前提下,动态修改定时任务的执行时间

    如何实现

    1、只需要两个依赖,也就是Spring boot项目最基本的依赖

    
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
                <version>2.7.0version>
            dependency>
    
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <version>1.18.20version>
                <scope>providedscope>
            dependency>
        dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2、启动类代码

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    /**
     * @author yuanchangliang
     * @date 2022/9/30
     */
    @EnableScheduling
    @SpringBootApplication
    public class DemoApplication {
     
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
            System.out.println("\n\n\n ★★★★ 动态修改定时任务 启动成功 ★★★★\n\n\n");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3、定时任务代码

    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 yuanchangliang
     * @date 2022/9/30
     */
    @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(this::doCorn, triggerContext -> {
                // 使用CronTrigger触发器,可动态修改cron表达式来操作循环规则
                CronTrigger cronTrigger = new CronTrigger(cron);
                return cronTrigger.nextExecutionTime(triggerContext);
            });
        }
    
        public void doCorn(){
            log.info("Current time: {}", LocalDateTime.now());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    4、corn表达式所在的配置文件:task-config.ini

    printTime.cron=0/10 * * * * ?
    
    • 1

    5、用于动态修改定时任务执行时间的接口:TestController.java

    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 yuanchangliang
     * @date 2022/9/30
     */
    @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";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    6、启动项目后,执行结果如下:
    在这里插入图片描述
    7、调用对外的修改定时任务的接口,执行结果如下:
    在这里插入图片描述

    项目结构

    在这里插入图片描述

    缺陷

    如果重启服务,将会重新读取配置文件中的cron表达式,所以通过接口进行修改定时任务的执行时间,只能在此次运行生效,重启即会重新读取读取配置文件中的配置。

    代码

    文章中的代码:https://gitee.com/judgebymom/dynamic-cron.git




    –我是“三七有脾气”,一个在互联网"苟且偷生"的Java程序员
    “如果感觉博客对你有用,麻烦给个点赞、评论、收藏,谢谢

  • 相关阅读:
    【Java高级技术】动态代理
    微服务系列二:微服务架构面临的挑战
    Python - Windows下使用Python脚本同步一个文件夹下的所有文件到另一个文件夹下
    vue+elementui个人健康信息网站php
    无线传感器网络的Z-SEP路由协议及对比(Matlab代码实现)
    国际法试题及答案
    用MATLAB求解微分方程
    基于单片机的机械臂运行轨迹在线控制系统设计
    那么多优秀的自动化测试工具,而你只知道Selenium?
    【Gitea】 Post “http://localhost:3000/api/internal/hook/pre-receive/aa/bbb“ 异常
  • 原文地址:https://blog.csdn.net/yuanchangliang/article/details/127125673