简体   繁体   中英

Different taskScheduler for different tasks

I'm using Spring and I've serveral @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 use a pool of 2 threads, while the second use a single thread. I don't want the second task is stuck because the first one use all threads available and the computation is slower than fixedDelay time. Of course mine is just an example to get you the idea.

I could use a configuration class like this:

@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 define a different configuration for each @Scheduled component though.

The first task does not require a pool of 2 threads.

Different tasks do not need to be assigned different pools if all using fixed delays. The fixedDelay works as follows:

@Scheduled(fixedDelay=5000)
public void doSomething() {
// something that should execute periodically
}

Would be invoked every 5 seconds with a fixed delay, meaning that the period will be measured from the completion time of each preceding invocation.

Each task only uses one thread, if you have two threads, one thread will not hold up the other to be useable for the other task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM