本文介绍了以编程方式使用Spring调度作业(动态设置fixedRate)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我有这个:
@Scheduled(fixedRate=5000)
public void getSchedule(){
System.out.println("in scheduled job");
}
我可以更改此项以使用对属性的引用
I could change this to use a reference to a property
@Scheduled(fixedRate=${myRate})
public void getSchedule(){
System.out.println("in scheduled job");
}
但是我需要使用以编程方式获得的值,以便可以在不更改的情况下更改计划重新部署应用程序。什么是最好的方法?我意识到使用注释可能是不可能的......
However I need to use a value obtained programmatically so the schedule can be changed without redeploying the app. What is the best way? I realize using annotations may not be possible...
推荐答案
使用你可以计算下一个执行时间飞行。
Using a Trigger
you can calculate the next execution time on the fly.
这样的事情可以解决问题(改编自):
Something like this should do the trick (adapted from the Javadoc for @EnableScheduling
):
@Configuration
@EnableScheduling
public class MyAppConfig implements SchedulingConfigurer {
@Autowired
Environment env;
@Bean
public MyBean myBean() {
return new MyBean();
}
@Bean(destroyMethod = "shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(100);
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
taskRegistrar.addTriggerTask(
new Runnable() {
@Override public void run() {
myBean().getSchedule();
}
},
new Trigger() {
@Override public Date nextExecutionTime(TriggerContext triggerContext) {
Calendar nextExecutionTime = new GregorianCalendar();
Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
nextExecutionTime.add(Calendar.MILLISECOND, env.getProperty("myRate", Integer.class)); //you can get the value from wherever you want
return nextExecutionTime.getTime();
}
}
);
}
}
这篇关于以编程方式使用Spring调度作业(动态设置fixedRate)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!