How to Schedule a Job with Spring Programmatically with Dynamically Set Fixed Rate
In Spring, tasks can be scheduled using annotations like @Scheduled. However, if the fixed rate needs to be changed dynamically without redeploying the application, a different approach is required.
One solution is to use a Trigger. With a trigger, you can calculate the next execution time on the fly based on a custom logic.
Here's an example of how to configure a trigger-based job using the ScheduledTaskRegistrar:
@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)); //Get the value dynamically return nextExecutionTime.getTime(); } } ); } }
This allows you to set the fixed rate dynamically using the Environment property. The myRate property can be retrieved from any source, such as a database or a configuration file.
The above is the detailed content of How to Dynamically Schedule Jobs with a Fixed Rate in Spring?. For more information, please follow other related articles on the PHP Chinese website!