programing

여러 스프링 @스케줄 태스크 동시 실행

newnotes 2023. 3. 31. 22:42
반응형

여러 스프링 @스케줄 태스크 동시 실행

스프링 부트 시 여러 스케줄링된 작업을 동시에 실행하려고 하지만 실제로는 큐잉이 실행됩니다(병행이 아닌 연속).

이것이 저의 간단한 서비스입니다.

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

를 사용해 주세요.TaskScheduler당신의 목적을 위해

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

어디에THREADS_COUNT- 병렬로 수행해야 할 작업의 총 수.내가 너를 정확히 이해한다면, 너는 직업이 2개밖에 없기 때문에 2개의 스레드가 필요해.

또는 application.properties에서 다음 속성을 구성할 수 있습니다.

spring.task.scheduling.pool.size=2

언급URL : https://stackoverflow.com/questions/44944038/multiple-spring-scheduled-tasks-simultaneously

반응형