用最简单的方式实现动态修改 Spring Boot 定时任务的执行时间

1,851 阅读2分钟

Spring Boot 动态修改定时任务的执行时间 cron

前提

大家通过Spring Boot跑定时任务,用的最多的是 @Scheduled,通过指定cron来定时的执行任务,cron可以使用SPEL表达式来通过配置文件配置,但是项目一旦启动,执行时间便无法修改,不够方便,本文基于此来优化项目启动之后不能动态修改cron的问题,实现任务执行时间可以通过Apollo等配置中心实时,动态的修改。

方案一

Spring 有提供 SchedulingConfigurer 接口来定制化定时任务,可以在new CronTrigger的时候放入一个动态的配置key来更改执行时间,优点是可以在项目启动后通过Apollo等配置中心动态的修改执行时间,缺点是一个定时任务就要新建一个类实现此接口,不够优雅。具体示例如下:

package com.ming.tiny.scheduling;
​
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
​
@Slf4j
@Component
public class TestSchedulingConfigurer implements SchedulingConfigurer {
​
​
    @Value("${testSchedulingConfigurer.cron=0/5 * * * * ?}")
    private String cron;
​
    private void testSchedulingConfigurer() {
        log.info("testSchedulingConfigurer 。。。");
    }
​
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(this::testSchedulingConfigurer, triggerContext -> {
            CronTrigger trigger = new CronTrigger(this.cron);
            return trigger.nextExecutionTime(triggerContext);
        });
    }
}
​

方案二

方案一可以在项目启动之后动态的修改cron,但是不够灵活,方案二在使用@Scheduled的情况下,结合SchedulingConfigurer来实现动态的修改cron,原理是通过ScheduledTaskRegistrar获取到所有的定时任务,判断哪些是动态配置的cron,把它拿出来通过方案一加入定时任务,共两种方式,如下:

  1. 自定义注解DynamicCron,指定某个任务为动态配置cron

        @DynamicCron(cronKey = "testAnnotation.cron")
        @Scheduled(cron = "${testAnnotation.cron:0/5 * * * * ?}")
        public void testAnnotation() {
            log.info("testAnnotation。。。");
        }
    
  2. cron 的 key 为方法的全路径且配置文件有配置时,则可以通过Apollo等配置中心动态调整执行时间

        /**
         * cron 的 key 为方法的全路径且配置文件有配置时,则可以通过Apollo等配置中心动态调整执行时间
         */
        @Scheduled(cron = "${com.ming.tiny.scheduling.TestScheduling.test}")
        public void test() {
            log.info("testScheduling。。。");
        }
    

具体实现如下:

package com.ming.tiny.scheduling;
​
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
​
@Retention(RetentionPolicy.RUNTIME)
public @interface DynamicCron {
​
    String cronKey();
​
}

主要实现逻辑如下:

package com.ming.tiny.scheduling;
​
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
​
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
​
@Slf4j
@Component
public class SchedulingConfig implements SchedulingConfigurer {
​
    @Autowired
    private Environment environment;
​
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        List<CronTask> cronTaskList = new ArrayList<>(taskRegistrar.getCronTaskList());
        Iterator<CronTask> iterator = cronTaskList.iterator();
        while (iterator.hasNext()) {
            CronTask cronTask = iterator.next();
            String fullPath = cronTask.toString();
            log.info("cronTaskList:{}", fullPath);
            DynamicCron dynamicCron = getDynamicCron(fullPath);
            String dynamicCronKey;
            if (Objects.isNull(dynamicCron)) {
                // 如果key为全路径,且配置文件有配置,则加入动态 Cron
                String cronExpression = this.environment.getProperty(cronTask.toString(), "");
                if (StringUtils.isNotBlank(cronExpression)) {
                    dynamicCronKey = cronTask.toString();
                } else {
                    dynamicCronKey = "";
                }
            } else {
                dynamicCronKey = dynamicCron.cronKey();
            }
            if (StringUtils.isNotBlank(dynamicCronKey)) {
                iterator.remove();
                taskRegistrar.addTriggerTask(cronTask.getRunnable(), triggerContext -> {
                    CronTrigger trigger = new CronTrigger(this.environment.getProperty(dynamicCronKey, cronTask.getExpression()));
                    return trigger.nextExecutionTime(triggerContext);
                });
                log.info("addTriggerTask:{}", cronTask);
            }
        }
        taskRegistrar.setCronTasksList(cronTaskList);
    }
​
    private DynamicCron getDynamicCron(String fullPath) {
        try {
            int lastDotIndex = fullPath.lastIndexOf('.');
            // 加载类
            Class<?> clazz = Class.forName(fullPath.substring(0, lastDotIndex));
            // 获取方法
            Method method = clazz.getDeclaredMethod(fullPath.substring(lastDotIndex + 1));
            // 获取注解
            return method.getAnnotation(DynamicCron.class);
        } catch (Exception e) {
            log.error("getAnnotation err", e);
            throw new RuntimeException(e);
        }
    }
}

测试用例如下:

package com.ming.tiny.scheduling;
​
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
​
@Slf4j
@EnableScheduling
@Component
public class TestScheduling {
​
    /**
     * cron 的 key 为方法的全路径且配置文件有配置时,则可以通过Apollo等配置中心动态调整执行时间
     */
    @Scheduled(cron = "${com.ming.tiny.scheduling.TestScheduling.test}")
    public void test() {
        log.info("testScheduling。。。");
    }
​
    /**
     * 像这种不是全路径的,无法解析,项目启动之后无法动态调整执行时间
     */
    @Scheduled(cron = "${testNoDynamic.cron:0/5 * * * * ?}")
    public void testNoDynamic() {
        log.info("testNoDynamic。。。");
    }
​
    @DynamicCron(cronKey = "testAnnotation.cron")
    @Scheduled(cron = "${testAnnotation.cron:0/5 * * * * ?}")
    public void testAnnotation() {
        log.info("testAnnotation。。。");
    }
​
}

总结

看过网上的一些实现方案,大多都比较复杂,仔细阅读 Spring 相关源码后,站在巨人的肩膀上,充分利用了 Spring 提供的 SchedulingConfigurer 接口,以最简单的方式实现了可通过Apollo等配置中心在项目启动之后动态的调整任务的执行时间,希望大家喜欢。