动态改变Spring定时任务执行频率

动态改变Spring定时任务执行频率

一.引入

    由于公司门户系统需要定时推送数据进国家平台,所以首先想到的是利用spring的定时任务进行定时推送,当然对于这种需求比较简单,如下操作即可:

    1.打开任务调度使用,在applicationContext.xml中添加  <task:annotation-driven />,即配置打开了任务调度

当然注意了:头文件上需要加上

<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:task="http://www.springframework.org/schema/task"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd   
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">



    2.自定义一个 任务调度的类,这里我写为了:MyScheduler.java ,为了让spring能够管理到,加上了Component注解,然后方法上加上Scheduled注解,进行配置调度的频率(1000*60)-代表1分钟调用一次

          @Component("scheduledTaskManager")
          public class MyScheduler {

           @Scheduled(fixedRate = 1000*60)
           public void heartbeat() {
        //任务逻辑

             }
         }


这样配置就结束了,很简单明了。


二.动态修改调度频率

    通过上述的配置,已经实现了简单的定时任务调度,但是这中写法不适宜动态修改,至少我还没有按照上述的写法动态修改频率成功过,于是,这里写一下另外一种写法:

    定义一个任务类:updateCronTask.java,这个类实现SchedulingConfigurer接口的configureTasks方法

    @Component
    @EnableScheduling
    public class updateCronTask implements SchedulingConfigurer {  
       
        public static String cron = "0/2 * * * * ?";  
        int i=0;
    
        @Override  
        public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
            taskRegistrar.addTriggerTask(new Runnable() {  
            @Override  
            public void run(){
            i++;
                // 任务逻辑  
            System.out.println("第"+(i)+"次开始执行操作... " +"时间:【" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS").format(new Date()) + "】");
                
            }
        }, new Trigger(){
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //任务触发,可修改任务的执行周期 
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;  
            }
        });
    }
}



项目启动后,只要触发改变cron的参数即可实现动态 修改任务调度频率,如:测试在controller层中,当访问了 某个url后,触发改变了cron 的参数,达到了预期的效果。

开始默认的频率是2s /次,后来通过controller层进行修改成了10s /次,


如果你有更好的方法,记得分享出来。



  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值