Multiple Spring @Scheduled Tasks at the Same Time

I try to run several scheduled tasks at the same time when spring boots, but in practice they start the sequence (one by one, not parallel)

This is my simple service:

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

Output:

 [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 

But, it should be like:

 [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 

What am I doing wrong?

This is my configuration:

 @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; } } 
+5
source share
1 answer

You must use TaskScheduler for your purpose.

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

Where THREADS_COUNT is the total number of tasks to be performed in parallel. If I understand you correctly, you only have 2 tasks, so you need 2 threads

+6
source

Source: https://habr.com/ru/post/1269549/


All Articles