【发布时间】:2020-03-07 22:03:53
【问题描述】:
我想实现多个@Scheduled(具有固定延迟)任务,每个任务都有自己的线程池。
@Scheduled(fixedDelayString = "30000")
public void createOrderSchedule() {
//create 10 orders concurrently; wait for all to be finished
createOrder(10);
}
@Scheduled(fixedDelayString = "30000")
public void processOrderSchedule() {
//process 10 orders concurrently; wait for all to be finished
}
@Scheduled(fixedDelayString = "30000")
public void notifySchedule() {
//send notification for 10 orders concurrently; wait for all to be finished
}
我设法为每个调度程序创建了不同的ThreadPoolTaskExecutor,如下所示:
@Bean("orderPool")
public ThreadPoolTaskExecutor createOrderTaskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(5);
pool.setMaxPoolSize(10);
pool.setThreadNamePrefix("order-thread-pool-");
pool.setWaitForTasksToCompleteOnShutdown(true);
return pool;
}
..
我为每个任务提供了@Async。
@Async("orderPool")
public void createOrder(Integer noOforders) {..}
和一个任务调度器配置
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(3);
return threadPoolTaskScheduler;
}
我使用CompletableFuture.allOf(..).join(); 等待每个任务完成,但它阻止了所有其他@Scheduled 任务。
综上所述,我想实现以下目标:
- 每个
@Scheduled任务都应独立运行,而不会阻塞其他@Scheduled任务。 - 每个
@Scheduled任务都应该有自己的线程池,以便它可以同时运行多个子任务(比如10 个)。 - 每个
@Scheduled任务都必须等待每个触发器完成而不被再次调用。
我怎样才能做到这一点?
【问题讨论】:
-
不,但我已经解决了,很快我会发布我的答案
标签: multithreading spring-boot scheduled-tasks threadpool spring-scheduled