Reputation: 411
In Spring Boot application I have several scheduled tasks. I want them to run simultaneously, so in my configuration I should create ThreadPoolTaskScheduler
object and register it in ScheduledTaskRegistrar
.
I find two ways to do that:
way 1
@Configuration
@EnableScheduling
public class SchedulerConfig implements SchedulingConfigurer {
private final int POOL_SIZE = 10;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(POOL_SIZE);
scheduler.setThreadNamePrefix("name");
scheduler.initialize();
scheduledTaskRegistrar.setTaskScheduler(scheduler);
}
}
way 2
@Configuration
@EnableScheduling
public class SchedulerConfig implements SchedulingConfigurer {
private final int POOL_SIZE = 10;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.setTaskScheduler(this.poolScheduler());
}
@Bean
public TaskScheduler poolScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(POOL_SIZE);
scheduler.setThreadNamePrefix("name");
return scheduler;
}
}
Upvotes: 3
Views: 8248
Reputation: 135
I was also tempted to define such a configuration. Since Spring Boot 2.1.0 you can do this via configuration (org.springframework.boot.autoconfigure.task.TaskSchedulingProperties
), both the number of threads and threadNamePrefix can be customised.
Upvotes: 0
Reputation: 290
Why in way 2 initialize method of ThreadPoolTaskScheduler object isn't called?
Because now, ThreadPoolTaskScheduler is a bean and it follows the Bean Life Cycle.
You can see that ThreadPoolTaskScheduler implements InitializingBean. So after spring builds this bean, it will call the afterPropertiesSet() method .
If you inspect the code of ThreadPoolTaskScheduler, you will see:
public void afterPropertiesSet() {
this.initialize();
}
Upvotes: 3
Reputation: 58774
Second way is better because you let Spring handle class TaskScheduler
and later you can use it in other classes using @Autowired
as:
@Autowired
TaskScheduler taskScheduler
Upvotes: 3