动态改变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 /次,


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



发布了48 篇原创文章 · 获赞 74 · 访问量 22万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章