不同任务的不同taskScheduler
Different taskScheduler for different tasks
我正在使用 Spring 并且在我的应用程序中有多个 @Scheduled classes:
@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
}
}
我希望第一个任务使用 2 个线程池,而第二个任务使用单个线程。我不希望第二个任务卡住,因为第一个任务使用所有可用线程并且计算速度比 fixedDelay
时间慢。
当然,我的例子只是让您了解的例子。
我可以使用这样的配置 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;
}
}
虽然我不明白如何为每个 @Scheduled 组件定义不同的配置。
第一个任务不需要 2 个线程池。
不同任务如果都使用固定延迟,则不需要分配不同的池。 fixedDelay
的工作原理如下:
@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.
每个任务只使用一个线程,如果你有两个线程,一个线程将不会占用另一个线程以用于另一个任务。
我正在使用 Spring 并且在我的应用程序中有多个 @Scheduled classes:
@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
}
}
我希望第一个任务使用 2 个线程池,而第二个任务使用单个线程。我不希望第二个任务卡住,因为第一个任务使用所有可用线程并且计算速度比 fixedDelay
时间慢。
当然,我的例子只是让您了解的例子。
我可以使用这样的配置 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;
}
}
虽然我不明白如何为每个 @Scheduled 组件定义不同的配置。
第一个任务不需要 2 个线程池。
不同任务如果都使用固定延迟,则不需要分配不同的池。 fixedDelay
的工作原理如下:
@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.
每个任务只使用一个线程,如果你有两个线程,一个线程将不会占用另一个线程以用于另一个任务。