Nacos实现动态加载定时任务时间
作者:重逢是最好的邂逅
这段文章介绍了如何在SpringBoot项目中动态配置cron表达式,融合了`@Scheduled`注解、`SchedulingConfigurer`接口和Lambda表达式三个关键词,详细解释了实现动态定时任务的方法,适合有经验的技术人员参考
前言
需要实现一个动态改变cron表达式的定时器任务。
我们知道Spring Boot要使用定时任务,就要在启动类上加上@EnableScheduling注解,并且在某个方法上加上@Scheduled(cron = “0 0 1 * * ?”)
这种普通的方式,注解中的cron是没办法改变的,不能自定义动态的。即使当你强行去定义一个cron变量时,也会提醒你需要用final static修饰。
但Spring提供了一个接口:SchedulingConfigurer,实现接口重写方法就可以动态配置cron。
配置类
package com.xxx.xxx.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "xxx",ignoreInvalidFields = true)
public class Config {
private Mm mm;
public static class Mm{
String cron;
public String getCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
}
}
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
//定时任务类
@Component
public class DynamicCronSchedule implements SchedulingConfigurer {
public void A() {
// 逻辑方法
}
//cron从nacos中获取
@Autowired
private Config config;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
// 定时器要做的功能,比如统计等等
A();
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
// 我这里放在了配置文件里,模拟动态配置,也可以放在数据库中,动态修改
return new CronTrigger(config.getCron()).nextExecutionTime(triggerContext);
}
});
}
}configureTasks方法
在java 8下可用Lamda表达式简化成
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(() -> {
A();
}, triggerContext -> new CronTrigger(config.getCron()).nextExecutionTime(triggerContext));
}在Springboot项目初始化时会执行A方法,并将B方法得到的cron表达式作为执行的时间点。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
