2017-07-06 2 views
5

Je suis en train d'exécuter plusieurs tâches planifiées en même temps au démarrage du printemps, mais en pratique, ils courent faire la queue (l'un après l'autre, non parallèle)tâches multiples Spring @Scheduled simultanément

Ceci est mon service simple :

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

sortie:

[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 

Mais, il devrait être comme:

[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 

Qu'est-ce que je fais mal?

C'est ma 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; 
    } 
} 
+1

Vous confondez 'TaskExecutor' avec' TaskScheduler' vous n'avez pas configuré ce dernier et donc tout fonctionne en mode de synchronisation (la valeur par défaut). –

+0

Merci @ M.Deinum !! – scheduleds

Répondre

6

Vous devez utiliser TaskScheduler pour votre but

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

THREADS_COUNT - Nombre total des tâches qui doivent être exécutées en parallèle. Si je vous comprends bien, vous avez seulement 2 tâches, donc vous avez besoin de 2 threads