Back-end/Spring Boot

[Spring Boot] Scheduler

Bay Im 2024. 4. 13. 12:50

Scheduler

  • 스케줄러 관련 어노테이션
    • @EnableAsync
      • 비동기적으로 처리하도록 제공하는 어노테이션
      • 각기 다른 스레드에서 실행된다.
    • @Async
      • 해당 메소드 로직이 시작되는 시간을 기준으로 milli sec 간격으로 실행
      • 이전 작업이 완료될 때까지 다음 작업이 진행되지 않음
    • @Scheduled(fixedRate = n)
      • 스케줄 옵션을 설정하는 어노테이션
      • 해당 어노테이션을 사용하면 일정한 시간 간격이나 특정 시간에 코드가 실행되도록 설정할 수 있다.
      • n에는 초를 설정하며, 값이 1000이면 1초이다.
      • 속성
        • fixedRate
          • 작업 수행시간과 상관없이 일정 주기마다 메소드 호출
        • fixedDelay
          • 작업을 마친 후부터 주기 타이머가 돌아 메소드 호출
        • initialDelay
          • 스케줄러에서 메소드가 등록되자마자 수행하는 것이 아닌 초기 지연시간을 설정
        • cron
          • Cron 표현식을 사용하여 작업 예약
          • 표현식은 6자리 설정만 허용하며 연도 설정은 할 수 없다.
            • 초(0~59) 분(0~59) 시간(0~23) 일(1~31) 월(1~12) 요일(0~7)
            • @Scheduled(cron = "* * * * * *")
          • 예시
            •     @Scheduled(cron = "0 15 10 15 * ?")
                  public void task3() {
                      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                      Date now = new Date();
                      String strDate = sdf.format(now);
                      log.info("cron task - {}", strDate);
                  }
  • 스케줄러 구현
    • Scheduler 클래스 생성
      • 클래스에 어노테이션 주입
        • @Component
        • @Slf4j
        • @EnableAsync
      • 메소드 생성
        • 메소드에 어노테이션 주입
          • @Scheduled(fixedRate = n)
        • throws InterruptedException으로 예외 처리
      • 예시
        • @Component
          @Slf4j
          @EnableAsync
          public class Scheduler {
              @Scheduled(fixedRate = 1000)
              public void task1() throws InterruptedException {
                  log.info("FixedRate task - {}", System.currentTimeMillis()/1000);
                  log.info("dead!");
              }
          }
  • 스레드 개수 설정
    • SchedulerCongif 클래스 생성
      • implements SchedulingConfigurer 후 configureTasks(ScheduledTaskRegristrar taskRegistrar) 함수 오버라이드
      • 예시
        • @Configuration
          public class SchedulerConfig implements SchedulingConfigurer {
          
              @Override
              public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
                  // Thread Pool 설정
                  ThreadPoolTaskScheduler threadPool = new ThreadPoolTaskScheduler();
          
                  // Thread 개수 설정
                  int n = Runtime.getRuntime().availableProcessors();
                  threadPool.setPoolSize(n);
                  threadPool.initialize();
          
                  taskRegistrar.setTaskScheduler(threadPool);
              }
          }
 
728x90