How do I tell my Spring scheduled method to run using a specific executor?
For example, this is one of my spring scheduler method,
@Scheduled(fixedRate=1000)
public void scheduleJobs(){
doThese();
}
And here are the 2 executors defined in my Java config:
@Bean
public Executor taskScheduler() {
ThreadPoolTaskScheduler t = new ThreadPoolTaskScheduler();
t.setPoolSize(2);
t.setThreadNamePrefix("taskScheduler - ");
t.initialize();
return t;
}
@Bean
public Executor newTaskScheduler() {
ThreadPoolTaskScheduler t = new ThreadPoolTaskScheduler();
t.setPoolSize(2);
t.setThreadNamePrefix("newTaskScheduler - ");
t.initialize();
return t;
}
When the scheduled method is running I can see it is using taskScheduler
executor. How to tell it to run using newTaskScheduler
executor?
The Javadoc of @EnableScheduling
is pretty exhaustive in that area.
You need to implement a SchedulingConfigurer
to fine-tune which Executor
needs to be used.
@Configuration
@EnableScheduling
public class AppConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskScheduler());
}
@Bean
public Executor taskScheduler() {
ThreadPoolTaskScheduler t = new ThreadPoolTaskScheduler();
t.setPoolSize(2);
t.setThreadNamePrefix("taskScheduler - ");
t.initialize();
return t;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With