scheduling사용하는데 같은 스케줄 작업이 동시에 실행되면 안 됐다.
찾아봤는데 stackoverflow에서도 의견이 다른 느낌도 있어서 찜찜해 직접 해 확인해 봤다.
@Scheduled에서는 이전 작업이 끝날 때까지 다음 작업이 진행되지 않는다.
그러니깐 같은 @Scheduled 메서드에 있는 작업은 동시에 진행되지 않는다.
- cron이든 fixedRate나 fixedDelay를 하든 이전 작업이 끝나지 않으면 다음 작업이 진행되지 않는다.
- 그러니 동시성 concurrentcy 문제는 신경 쓰지 않아도 된다.
- 다만, application을 1개가 아니라 2개 이상 동시에 사용하게 된다면 같은 스케줄이 발생할 수 있다. (당연하겠지만)
[ Example 예시 ]
- 5초마다 돌아가는 스케줄 작업 → 안에 for문이 끝날 때까지 (약 10초) 같은 스케줄의 작업이 비동기적으로 실행되지 않는다.
- 참고 : Thread.sleep()은 스케줄 시간에 영향을 안 준다.
@Scheduled(cron = "${spring.schedule.cron}") // 0/5 * * * ? 5초마다
public void exampleSchedule1() {
for(int i=0;i < 10; i++){
Thread.sleep(1000);
}
}
@Scheduled(cron = "${spring.schedule.cron}") // 0/4 * * * ? 5초마다
public void exampleSchedule2() {
Thread.sleep(1000);
}
- @Scheduled가 따로 되어 있는 것은 Scheduling pool size에 따라 비동기적으로 실행된다. (pool size 안 정해도 스케줄에서 알아서 pool 만들어줌)
- 즉, exampleSchedule1과 exampleSchedule2는 비동기적으로 실행이 가능하다. → exampleSchedule1이 실행이 안 끝나도 exampleSchedule2는 스케줄 시간에 맞게 실행할 수 있다.
이전 작업이 끝나는 것과 관계없이 다음 작업을 진행하고 싶다면..
- @Async를 사용
@Async
@Scheduled(cron = "${spring.schedule.cron}") // 0/5 * * * ? 5초마다
public void exampleSchedule() {
for(int i=0;i < 10; i++){
Thread.sleep(1000);
}
}
[ 참고 링크 ]
https://stackoverflow.com/questions/24033208/how-to-prevent-overlapping-schedules-in-spring
How to prevent overlapping schedules in Spring?
@Scheduled(fixedDelay = 5000) public void myJob() { Thread.sleep(12000); } How can I prevent this spring job from running if the previous routine is not yet finished?
stackoverflow.com
ScheduledThreadPoolExecutor (Java Platform SE 8 )
A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPool
docs.oracle.com
https://hackernoon.com/mastering-scheduling-and-tax-execution-in-spring-boot
Mastering Scheduling and Tax Execution in Spring Boot | HackerNoon
Discover the ins and outs of Spring Scheduler, covering annotations, examples, cron expressions, fixed delays, and more for task automation in spring.
hackernoon.com
https://stackoverflow.com/questions/24033208/how-to-prevent-overlapping-schedules-in-spring
How to prevent overlapping schedules in Spring?
@Scheduled(fixedDelay = 5000) public void myJob() { Thread.sleep(12000); } How can I prevent this spring job from running if the previous routine is not yet finished?
stackoverflow.com