• SpringBoot设置动态定时任务


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

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

    因为只是一个demo,所以只引入了需要的依赖:

    
            
                org.springframework.boot
                spring-boot-starter-web
            
    
            
                org.springframework.boot
                spring-boot-starter-log4j2
                true
            
    
            
            
                org.springframework.boot
                spring-boot-starter-validation
            
    
            
                org.projectlombok
                lombok
                true
            
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    启动类:

    package com.wl.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    /**
     * @author wl
     * @date 2022/3/22
     */
    @EnableScheduling
    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
            System.out.println("(*^▽^*)启动成功!!!(〃'▽'〃)");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    配置文件application.yml,只定义了服务端口:

    server:
      port: 8089
    
    • 1
    • 2

    定时任务执行时间配置文件:task-config.ini:

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

    定时任务执行类:

    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
     * @date 2022/3/22
     */
    @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;
                }
            });
        }
    }
    
    • 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
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

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

    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
     * @date 2022/3/22
     */
    @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
    • 30
    • 31
    • 32

    启动项目,可以看到任务每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
     * @date 2022/3/22
     */
    @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;
                }
            });
        }
    }
    
    • 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
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

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

    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
     * @date 2022/3/22
     */
    @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";
        }
    }
    
    • 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

    测试结果:

    先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

  • 相关阅读:
    ArcGIS Pro怎么进行挖填方计算
    基于PHP+MySQL的大学生就业指导人力资源网
    STL教程4-输入输出流和对象序列化
    企业该如何选择自己合适的云财务软件?
    医院电子病历编辑器,EMRE(EMR Editor)源码
    C陷阱与缺陷 第7章 可移植性缺陷 7.2 标识符名称的限制
    Acwing.889 满足条件的01序列
    Netty-RPC
    找不到msvcr100.dll怎么办?三种方法教你
    AtCoder ABC001D - 感雨時刻の整理 题解及翻译(差分,排序,占位输出方式)
  • 原文地址:https://blog.csdn.net/m0_67390969/article/details/126115425