gpt4 book ai didi

spring - 多个 Spring @Scheduled 任务同时进行

转载 作者:行者123 更新时间:2023-12-04 03:19:12 24 4
gpt4 key购买 nike

我试图在 Spring 启动时同时运行多个计划任务,但实际上它们运行排队(一个接一个,而不是并行)

这是我的简单服务:

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
[A] Done the cycle of scheduled task
[B] Starting new cycle of scheduled task
[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;
}
}

最佳答案

或者,您可以在 application.properties 中配置此属性:

spring.task.scheduling.pool.size=2

关于spring - 多个 Spring @Scheduled 任务同时进行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44944038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com