关于spring:如何动态注册或注销Scheduled-cron定时任务

0次阅读

共计 3743 个字符,预计需要花费 10 分钟才能阅读完成。

实在业务场景

Spring 中,@Scheduled 能够通过读取配置或者硬编码的形式指定 cron 表达式,来实现触发某个工夫的定时工作的性能
但咱们须要不重启服务,来实现动静地批改定时工作的触发工夫,原有性能无奈实现。

@Scheduled 原理

  1. @EnableScheduling注解引入 SchedulingConfiguration 配置类
  2. SchedulingConfiguration 注册 ScheduledAnnotationBeanPostProcessor Scheduled 注解后处理器实例
  3. ScheduledAnnotationBeanPostProcessor#postProcessAfterInitializationScheduled注解后处理器扫描带
    org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor#postProcessAfterInitialization
    @Scheduled 的办法 依据注解中定义的属性,构建并注册定时工作

实现思路

  1. 找到 Scheduled 注解后处理器 注册的局部,查看源码
    a. 是否预留可扩大的局部(例如 局部存在逻辑转发,转发到其余接口实例或者其余形象办法)
    b. 是否能够继承
    c. 要害办法是否为 protected
    d. 应用反射(下下策)
  2. 找到扩大办法,封装 注册 / 登记逻辑

具体实现思路

  1. 定时工作注册逻辑在 ScheduledAnnotationBeanPostProcessor#processScheduled 办法中,办法为 protected,创立子类,能够拜访该办法。
  2. 办法须要传入 Scheduled 注解实例,创立代理,构建注解对象实例
    a. 寻找现有框架逻辑

     i. 寻找 Annotation 结尾的 Utils 办法、Factory 办法
     ii. hibernate 存在相似办法 `AnnotationDescriptor.Builder` 能够构建 `org.hibernate.validator.internal.util.annotation.AnnotationFactory#create`
     iii. Spring 框架存在相似办法 `org.springframework.core.annotation.AnnotationUtils#synthesizeAnnotation(java.util.Map<java.lang.String,java.lang.Object>, java.lang.Class<A>, java.lang.reflect.AnnotatedElement)`

    b. 拷贝框架逻辑(上策)
    c. 本人编写创立代理实例(下下策)

  3. 定时工作登记相似逻辑在ScheduledAnnotationBeanPostProcessor#postProcessBeforeDestruction
    a. scheduledTasks 公有属性无法访问,只能应用反射

具体代码逻辑

import com.google.common.collect.Maps;
import org.redisson.liveobject.misc.ClassUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

import static java.util.Collections.emptySet;

/**
 * @author fuhangbo
 */
@Component
public class ConfigurableScheduler {
    private final InnerScheduledAnnotationBeanPostProcessor postProcessor;

    public ConfigurableScheduler(InnerScheduledAnnotationBeanPostProcessor postProcessor) {this.postProcessor = postProcessor;}

    public void registerScheduleTask(String cron, Method method, Object target) {Map<String, Object> attributes = Maps.newHashMap();
        attributes.put("cron", cron);
        // 构建 Scheduled 注解实例
        Scheduled scheduled = AnnotationUtils.synthesizeAnnotation(attributes, Scheduled.class, null);
        postProcessor.registerScheduleTask(scheduled, method, target);
    }

    public void unregister(String cron, Object target) {postProcessor.unregister(target, cron);
    }

    @Component
    public static class InnerScheduledAnnotationBeanPostProcessor extends ScheduledAnnotationBeanPostProcessor {

        private final Map<Object, Set<ScheduledTask>> scheduledTasksMap;

        public InnerScheduledAnnotationBeanPostProcessor() {
            // ScheduledAnnotationBeanPostProcessor 不提供 remove 某个工作的逻辑
            // 实现登记定时工作 须要拜访 scheduledTasks 属性,然而 ScheduledAnnotationBeanPostProcessor 中为公有,因而只能应用反射或者 scheduledTasks 实例
            scheduledTasksMap = ClassUtils.getField(this, "scheduledTasks");
        }

        public void registerScheduleTask(Scheduled scheduled, Method method, Object bean) {
            // 调用父类 prtotected 办法
            super.processScheduled(scheduled, method, bean);
        }

        public void unregister(Object bean, String cron) {synchronized (scheduledTasksMap) {Set<ScheduledTask> tasks = getScheduledTasks();
                for (ScheduledTask task : tasks) {if (task.getTask() instanceof CronTask
                            // cron 表达式雷同时,勾销并从 scheduledTasks 中的实例
                            && ((CronTask) task.getTask()).getExpression().equals(cron)) {task.cancel();
                        scheduledTasksMap.getOrDefault(bean, emptySet()).remove(task);
                    }
                }
            }
        }
    }
}

最终成果

// cron 变更 登记
public modifyScheduleTask(String newCron, String oldCron) {if (oldCron!= null && !oldCron.equals(newCron)) {Method xxxMethod = ClassUtils.getMethod(StatisticsSchedules.class, "xxxMethod");
            configurableScheduler.unregister(oldCron, this);
            if (newCron != null) {configurableScheduler.registerScheduleTask(newCron, xxxMethod, this);
            }           
    }
}

public void xxxMethod() {
  // 定时工作办法
  // do something...
}
正文完
 0