spring动态配置cron表达式,不需要停服
2018-10-25 本文已影响0人
zxydut
spring做定时任务调度时有常用的两种方式,分别是基于配置文件的quartz和基于注解的@Scheduler。quartz需要较多的配置文件,个人感觉比较麻烦,@Scheduler注解只需要简单的配置即可,但是这两种发方法不能动态加载cron表达式,每次更改调度规则都需要重启服务。本文介绍一种不需要重启服务的动态加载cron表达式的方法。
使用SchedulingConfigurer 接口来实现动态加载cron表达式。
代码示例如下:
@Component
@EnableScheduling
public class Test implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
//创建一个线程池调度器,默认是单线程执行
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(100);
scheduledTaskRegistrar.setScheduler(executorService);
//增加任务
scheduledTaskRegistrar.addTriggerTask(new Task("test1"),new Trig("cronExpess1"));
scheduledTaskRegistrar.addTriggerTask(new Task("test2"),new Trig("cronExpess2"));
scheduledTaskRegistrar.addTriggerTask(new Task("test3"),new Trig("cronExpess2"));
}
}
/**
* 业务类
*/
class Task implements Runnable{
String task;
public Task(String task){
this.task = task;
}
//具体业务
@Override
public void run() {
System.out.println(task+":"+LocalDateTime.now()+","+Thread.currentThread().getName());
}
}
/**
* 调度类
*/
class Trig implements Trigger{
private String cronExpress;
public Trig(String cronExpress){
this.cronExpress = cronExpress;
}
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
String cron = null;
try {
//每次调度时加载cron表达式
cron = new Config().getCrons().get(cronExpress);
} catch (IOException e) {
e.printStackTrace();
}
CronTrigger cronTrigger = new CronTrigger(cron);
return cronTrigger.nextExecutionTime(triggerContext);
}
}
/**
* 加载cron表达式
*/
class Config{
private static Map<String,String> cronMap;
private static long preModifyTime;
private String cronFile = "config/application.properties";
public Map<String,String> getCrons() throws IOException {
File file = new File(cronFile);
long nowModifyTime = file.lastModified();
if (cronMap != null && nowModifyTime == preModifyTime){
return cronMap;
}else {
cronMap = new HashMap<>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null){
String[] s = line.split("=");
cronMap.put(s[0].trim(),s[1].trim());
}
preModifyTime = nowModifyTime;
return cronMap;
}
}
}
配置文件:
cronExpess1 = 0/5 * * * * *
cronExpess2 = 0/10 * * * * *
运行结果(为了查看方便,只运行一个任务):
TIM截图20181025092416.png