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

实在业务场景

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...
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理