以编程方式使用 Spring 调度作业(使用 fixedRate 动态设置) [英] Scheduling a job with Spring programmatically (with fixedRate set dynamically)
本文介绍了以编程方式使用 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(fixedRateString="${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...
推荐答案
使用 Trigger
你可以即时计算下一次执行时间.
Using a Trigger
you can calculate the next execution time on the fly.
这样的事情应该可以解决问题(改编自 @EnableScheduling
的 Javadoc):
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 动态设置)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文