dripto
dripto

Reputation: 619

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?

Upvotes: 16

Views: 11981

Answers (3)

kuhajeyan
kuhajeyan

Reputation: 11037

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


}

Upvotes: 11

Gaurav Gupta
Gaurav Gupta

Reputation: 123

Executor qualification with @Scheduled is not supported yet.

Refer - https://jira.spring.io/browse/SPR-14218

Upvotes: 5

Stephane Nicoll
Stephane Nicoll

Reputation: 33131

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.

Upvotes: 10

Related Questions