Nacos实现动态加载定时任务时间
前言
需要实现一个动态改变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表达式作为执行的时间点。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Springboot中RedisTemplate设置String、Hash、List过期时间
本文主要介绍了Springboot中RedisTemplate设置String、Hash、List过期时间,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2024-05-05
Spring Security 基于URL的权限判断源码解析
这篇文章主要介绍了Spring Security 基于URL的权限判断问题,我们想要实现自己的基于请求Url的授权只需自定义一个 AccessDecisionManager即可,接下来跟随小编一起看看实现代码吧2021-12-12


最新评论