sch*_*eds 9 spring scheduled-tasks spring-boot
我试图在春季启动的同时运行多个计划任务,但实际上他们运行排队(一个接一个,不是并行)
这是我的简单服务:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
[A] Starting new cycle of scheduled task
[A] Done the cycle of scheduled task
[B] Starting new cycle of scheduled task
[B] Done the cycle of scheduled task
Run Code Online (Sandbox Code Playgroud)
但是,应该是这样的:
[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
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
这是我的配置:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
Dep*_*zor 24
或者,您可以在 application.properties 中配置此属性:
spring.task.scheduling.pool.size=2
Run Code Online (Sandbox Code Playgroud)
Myk*_*nko 15
你应该TaskScheduler用于你的目的
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(THREADS_COUNT);
return threadPoolTaskScheduler;
}
Run Code Online (Sandbox Code Playgroud)
其中THREADS_COUNT- 应并行执行的任务总数.如果我理解正确,你只有2个工作,所以你需要2个线程
| 归档时间: |
|
| 查看次数: |
8300 次 |
| 最近记录: |