同时执行多个Spring @Scheduled任务

时间:2017-07-06 08:49:31

标签: spring spring-boot scheduled-tasks

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

这是我的简单服务:

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;
    }
}

1 个答案:

答案 0 :(得分:13)

您应该将TaskScheduler用于您的目的

@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
    ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    threadPoolTaskScheduler.setPoolSize(THREADS_COUNT);
    return threadPoolTaskScheduler;
}

其中THREADS_COUNT - 应并行执行的任务总数。如果我理解正确,你只有2个工作,所以你需要2个线程