Java – different taskschedulers for different tasks
I am using spring. I have several @ scheduled classes in my application:
@Component public class CheckHealthTask { @Scheduled(fixedDelay = 10_000) public void checkHealth() { //stuff inside } } @Component public class ReconnectTask { @Scheduled(fixedDelay = 1200_000) public void run() { //stuff here } }
I want the first task to use two thread pools and the second task to use a single thread I don't want the second task to get stuck because the first task uses all available threads and is slower than the fixed delay time Of course, mine is just an example to let you understand this idea
I can use this configuration class:
@Configuration @EnableScheduling public class TaskConfig 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; } }
I don't understand how to define different configurations for each @ scheduled component
Solution
The first task does not require a pool of 2 threads
If all use fixed delays, there is no need to assign different tasks to different tasks The working principle of fixeddelay is as follows:
@Scheduled(fixedDelay=5000) public void doSomething() { // something that should execute periodically }
Each task uses only one thread. If you have two threads, one thread will not prevent the other thread from being available for another task