Search code examples
javaspringspring-bootquartz-scheduler

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?


Solution

  • 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.