Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring's @Scheduled annotation with a specific executor

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?

like image 813
Dripto Avatar asked Dec 07 '16 12:12

Dripto


2 Answers

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.

like image 188
Stephane Nicoll Avatar answered Nov 02 '22 23:11

Stephane Nicoll


@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;
 }


}
like image 27
kuhajeyan Avatar answered Nov 03 '22 01:11

kuhajeyan