同时执行多个Spring@计划任务
我试图在spring boot上同时运行多个计划任务,但实际上它们运行队列(一个接一个,而不是并行) 这是我的简单服务:同时执行多个Spring@计划任务,spring,spring-boot,scheduled-tasks,Spring,Spring Boot,Scheduled Tasks,我试图在spring boot上同时运行多个计划任务,但实际上它们运行队列(一个接一个,而不是并行) 这是我的简单服务: import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class MyScheduleDemo { @Scheduled(fixedDelay = 5000, initial
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class MyScheduleDemo {
@Scheduled(fixedDelay = 5000, initialDelay = 1000)
public void taskA() throws InterruptedException {
System.out.println("[A] Starting new cycle of scheduled task");
// Simulate an operation that took 5 seconds.
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime <= 5000);
System.out.println("[A] Done the cycle of scheduled task");
}
@Scheduled(fixedDelay = 5000, initialDelay = 2000)
public void taskB() throws InterruptedException {
System.out.println("[B] Starting new cycle of scheduled task");
System.out.println("[B] Done the cycle of scheduled task");
}
}
但是,它应该是这样的:
[A] Starting new cycle of scheduled task
[B] Starting new cycle of scheduled task
[B] Done the cycle of scheduled task
[A] Done the cycle of scheduled task
我做错了什么
这是我的配置:
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(6);
executor.setMaxPoolSize(50);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("customer-Executor-");
executor.initialize();
return executor;
}
}
您应该使用
TaskScheduler
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(THREADS_COUNT);
return threadPoolTaskScheduler;
}
其中
THREADS\u COUNT
-应并行执行的任务总数。如果我理解正确,您只有2个作业,因此需要2个线程您将TaskExecutor
与TaskScheduler
混淆,因为您没有配置后者,因此所有作业都以同步模式运行(默认)。谢谢@M.Deinum!!请记住,每个默认的@Async
注释也使用此调度器。如果使用@Scheduled
并调用@Async
方法,则在线程可用之前不会执行这些方法。
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(THREADS_COUNT);
return threadPoolTaskScheduler;
}