千家信息网

如何使用spring-task定时任务动态配置修改执行时间

发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,小编给大家分享一下如何使用spring-task定时任务动态配置修改执行时间,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!spring-task定时任务动态配置修改执行时间因项目需要
千家信息网最后更新 2026年11月03日如何使用spring-task定时任务动态配置修改执行时间

小编给大家分享一下如何使用spring-task定时任务动态配置修改执行时间,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

spring-task定时任务动态配置修改执行时间

因项目需要,几个定时任务需要人为动态设置执行时间,于是乎吧,就查阅相关资料,是可以动态设置的,废话不多说,直接上代码,一目了然。

package com.seckill.quartz;import org.springframework.scheduling.Trigger;import org.springframework.scheduling.TriggerContext;import org.springframework.scheduling.annotation.EnableScheduling;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.text.SimpleDateFormat;import java.util.Date; /** * Created by loup on 2017/11/11. */@Component@EnableSchedulingpublic class DynamicScheduledTask implements SchedulingConfigurer {    //时间表达式  每2秒执行一次    private String cron = "0/2 * * * * ?";    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");     @Override    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {        scheduledTaskRegistrar.addTriggerTask(new Runnable() {            @Override            public void run() {                //任务逻辑                System.out.println("---------------start-------------------");                System.out.println("动态修改定时任务参数,时间表达式cron为:" + cron);                System.out.println("当前时间为:" + sdf.format(new Date()));                System.out.println("----------------end--------------------");            }        }, new Trigger() {            @Override            public Date nextExecutionTime(TriggerContext triggerContext) {                CronTrigger cronTrigger = new CronTrigger(cron);                Date nextExecDate = cronTrigger.nextExecutionTime(triggerContext);                return nextExecDate;            }        });    }     public void setCron(String cron) {        this.cron = cron;    }}

这个是定时任务调度执行器,采用的是注解的方式。首先要动态配置,要设置为@EnableScheduling,这是确保能够动态,然后实现SchedulingConfigurer,重写configureTasks方法,接下来就是这个的相关spring配置文件,要引入下面这个task,不然识别不了啊,配置文件就是这么简单

http://www.springframework.org/schema/task

           

接下来就是写测试类,测试可不可行啊

package com.seckill.quartz;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.io.IOException; /** * Created by loup on 2017/11/11. */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration({"classpath*:/conf/spring-quartz.xml"})public class QuartzTest {     @Autowired    private DynamicScheduledTask dynamicScheduledTask;     @Test    public void test1(){        try {            Thread.sleep(10000);        } catch (InterruptedException e) {            e.printStackTrace();        }        dynamicScheduledTask.setCron("0/10 * * * * ?");        try {            System.in.read();        } catch (IOException e) {            e.printStackTrace();        }    }}

运行测试类,查看结果,达到效果,亲测可用

spring schedule 动态配置执行时间

之前saas平台实现动态修改定时任务的时间,都是通过xx-job这样的框架来实现,这样我们可以单独一个服务来管理我们整个saas平台的定时任务,但是最近给银行做的一个小项目,需要本地化部署,所以我不想弄很多的服务,并且他们并没有要求修改以后即时生效,所以我直接采用了 spring schedule结合mysql动态配置执行时间。

之前我们用的schedule通过注解的方式,只能用静态的corn表达式,如果想实现动态的需要实现SchedulingConfigurer,并且通过注解@EnableScheduling。如下:

package com.zqf.marketing.task;  import com.zqf.db.marketingrobot.sys.model.RobotSysSwitch;import com.zqf.marketing.sys.service.SwitchService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Lazy;import org.springframework.scheduling.Trigger;import org.springframework.scheduling.TriggerContext;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.SchedulingConfigurer;import org.springframework.scheduling.config.ScheduledTaskRegistrar;import org.springframework.scheduling.support.CronTrigger;import org.springframework.stereotype.Service; import java.util.Date; /** * @author zhenghao * @description * @date 2019/1/22 21:50 */ @Lazy(false)@Service@EnableSchedulingpublic class TestTaskService implements SchedulingConfigurer {     private static Logger log = LoggerFactory.getLogger(TestTaskService.class);    @Autowired    private SwitchService switchService;      private String SpringDynamicCronTask() {        String cron = "0/5 * * * * ?";        //从数据库获得配置的corn表达式        RobotSysSwitch switchById = switchService.getSwitchById(5L);        cron = switchById.getSwitchFlag();        log.info(cron);        return cron;    }      @Override    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {        scheduledTaskRegistrar.addTriggerTask(new Runnable() {            @Override            public void run() {                // 任务逻辑                log.info("task_task_tak");            }        }, new Trigger() {            @Override            public Date nextExecutionTime(TriggerContext triggerContext) {                String s = SpringDynamicCronTask();                // 任务触发,可修改任务的执行周期                CronTrigger trigger = new CronTrigger(s);                Date nextExec = trigger.nextExecutionTime(triggerContext);                return nextExec;            }        });      }}

看完了这篇文章,相信你对"如何使用spring-task定时任务动态配置修改执行时间"有了一定的了解,如果想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!

任务 动态 时间 配置 表达式 就是 注解 测试 接下来 平台 文件 方式 篇文章 逻辑 项目 服务 可行 一目了然 可不 代码 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 花魁咖啡 互联网巨头科技公司 互联网科技社 科技与互联网的利与弊 中国航天科技大学国际工业互联网 宜昌元轩互联网科技有限公司 开一家科技互联网公司需要多少钱 亳州好赞互联网科技有限公司 互联网金融科技展 深圳市罗太互联网科技有限公司 互联网科技圈年度人物 山东星卡互联网科技有限公司官网 互联网企业科技类企业如何做账 珠海东科互联网科技有限公司 中国新注册互联网科技 万物互联网智能科技 互联网界的黑科技 艺电能源互联网科技有限公司招聘 银川新华互联网科技学校招聘 伍佰万互联网科技是干嘛的 互联网科技工作委员会毛军 圆梦互联网科技 卓越科技(互联网 ) 上海喔噻互联网科技 上游互联网科技 健康食品互联网创新科技园项目 互联网科技和法律行业 华中科技大学互联网的牛人 21世纪互联网科技成就 安徽零酒互联网科技有限公司
0