目前我有这个:
@Scheduled(fixedRate=5000) public void getSchedule(){ System.out.println("in scheduled job"); }
我可以更改它以使用对属性的引用
@Scheduled(fixedRate=${myRate}) public void getSchedule(){ System.out.println("in scheduled job"); }
但是,我需要使用通过编程获得的值,以便可以在不重新部署应用程序的情况下更改计划。什么是最好的方法?我意识到可能无法使用注释…
使用a Trigger可以动态计算下一次执行时间。
a Trigger
这样的事情应该可以解决问题(从Javadoc@EnableScheduling改编为):
Javadoc@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(); } } ); } }