2017-07-06 16 views
5

Próbuję uruchomić wiele zadań zaplanowanych w tym samym czasie na starcie wiosny, ale w praktyce biegają kolejkowanie (jeden po drugim, a nie równolegle)wielu zadań jednocześnie Wiosna @Scheduled

To moja prosta obsługa :

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

wyjściowa:

[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 

Ale powinno to być tak:

[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 

Co robię źle?

To jest moja konfiguracja:

@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

Mylisz 'TaskExecutor' z' TaskScheduler', którego nie skonfigurowałeś, a zatem wszystko działa w trybie synchronizacji (domyślnie). –

+0

Dzięki @ M.Deinum !! – scheduleds

Odpowiedz

6

Należy użyć TaskScheduler dla celów

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

Gdzie THREADS_COUNT - całkowita liczba zadań, które powinny być wykonywane równolegle. Jeśli rozumiem cię poprawnie, masz tylko 2 zadania, więc potrzebujesz 2 wątków

Powiązane problemy