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

标签 spring spring-boot scheduled-tasks

我试图在 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/

相关文章:

Spring Websocket STOMP 负载测试

java - Web 应用程序中的 Spring bean 初始化

java - Spring分别缓存列表中的所有元素

java - 自动连线,值注释不起作用

python - 如何在不使用信用卡或没有钱的情况下在 Heroku 中安排 Django 后台任务?

java - 我们如何安排任务 24 小时执行并在变量中存储 24 小时响应?

java - 使用 rowmapper 读取值时语法错误 SQL 异常

java - Spring 依赖注入(inject) : Inject all instances of interface

java - Spring 严格传输安全(HSTS)配置不起作用

operating-system - Linux 内核中的调度策略