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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>