[SpringBoot] 스프링부트 스케줄러 @Scheduled, @EnableSchedule

SihoonCho·2023년 7월 15일
0
post-thumbnail

📌 @EnableScheduling


  • Main Application Class에 @EnableScheduling 추가
  • org.springframework.boot:spring-boot-starter 기본 내장
package com.project.projectname;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@SpringBootApplication
public class ProjectNameApplication {

    public static void main(String[] args) {
        SpringApplication.run(rojectNameApplication.class, args);
    }
    
}
  • @Scheduled 사용 규칙
    • Class에 @Component
    • Method에 @Scheduled
      • Method는 void 타입
      • Method는 매개변수 사용불가

📌 @Scheduled


  • @Scheduled 병렬 사용 방법
    • Class에는 @EnableAsync 추가
    • Method에는 @Async 추가

📖 fixedDelay & fixedDelayString


  • 이전 작업이 완료될 때까지 대기
  • 메서드 종료시간 기준, milliseconds 간격으로 실행
  • 하나의 인스턴스만 항상 실행되도록 해야 할 상황에서 유용
  • milliseconds 타입에 따라 정수이면 fixedDelay 문자열이면 fixedDelayString
@Scheduled(fixedDelay = 1000)
public void scheduledFixedDelayTest() throws InterruptedException {
    log.info("Fixed Delay Test: {}", System.currentTimeMillis() / 1000);
    Thread.sleep(5000);
}
// 문자열 milliseconds를 사용할 때
@Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds}")
public void scheduledFixedDelayStringTest() throws InterruptedException {
    log.info("Fixed Delay String Test: {}", System.currentTimeMillis() / 1000);
    Thread.sleep(5000);
}

📖 fixedRate & fixedRateString


  • 이전 작업이 완료될 때까지 대기
  • 메서드 시작시간 기준, milliseconds 간격으로 실행
  • 모든 실행이 독립적인 경우에 유용
  • milliseconds 타입에 따라 정수이면 fixedRate 문자열이면 fixedRateString
@Scheduled(fixedRate = 1000)
public void scheduledFixedRateTest() throws InterruptedException {
    log.info("Fixed Rate Test: {}", System.currentTimeMillis() / 1000);
    Thread.sleep(5000);
}
// 문자열 milliseconds를 사용할 때
@Scheduled(fixedRateString = "${fixedRate.in.milliseconds}")
public void scheduledFixedRateStringTest() throws InterruptedException {
    log.info("Fixed Rate String Test: {}", System.currentTimeMillis() / 1000);
    Thread.sleep(5000);
}

📖 initialDelay & initialDelayString


  • 초기 지연 시간으로 최초 실행시에만 적용되는 지연 시간
  • fixedDelay 혹은 fixedRate 등의 고정 시간값과 함께 사용
  • initialDelay 시간 이후 최초 실행, 이후 fixedDelay 시간마다 실행
  • milliseconds 타입에 따라 정수이면 initialDelay 문자열이면 initialDelayString
// 1초 대기 후 메서드 종료시간 기준으로 5초마다 반복
@Scheduled(fixedDelay = 5000, initialDelay = 1000)
public void scheduledFixedDelayWithInitialDelayTest() {
    long now = System.currentTimeMillis() / 1000;
    log.info("Initial Delay with Fixed Delay Test: {}", now);
}
// 1초 대기 후 메서드 시작시간 기준으로 5초마다 반복
@Scheduled(fixedRate = 5000, initialDelayString = "1000")
public void scheduledFixedRateWithInitialDelayTest() {
    long now = System.currentTimeMillis() / 1000;
    log.info("Initial Delay with Fixed Rate Test: {}", now);
}

📖 Cron & Zone


  • Cron 표현식을 통해 매 특정 시점마다 실행
    • Cron: "* * * * * *"
    • 초(0-59) 분(0-59) 시간(0-23) 일(1-31) 월(1-12) 요일(0-7)
  • Zone = "Asia/Seoul"
    • DefaultLocal 시간대 사용
@Scheduled(cron = "0 15 10 15 * ?") // 매월 15일 오전 10시 15분 실행
// @Scheduled(cron = "0 15 10 15 11 ?") // 11월 15일 오전 10시 15분 실행
// @Scheduled(cron = "${cron.expression}")
public void scheduledCronExpressionTest() {
    long now = System.currentTimeMillis() / 1000;
    log.info("Scheduled with Cron Expression Test: {}", now);
}
// 유럽/파리 시간 기준 매월 15일 오전 10시 15분 실행
@Scheduled(cron = "0 15 10 15 * ?", zone = "Europe/Paris")
public void scheduledCronExpressionWithZoneTest() {
    long now = System.currentTimeMillis() / 1000;
    log.info("Scheduled with Cron Expression and Zone Test: {}", now);
}

📌 Summary


📋 fixedDelay & fixedDelayString


  • 이전 작업이 완료될 때까지 대기
  • 메서드 종료시간 기준, milliseconds 간격으로 실행
  • 하나의 인스턴스만 항상 실행되도록 해야 할 상황에서 유용
  • milliseconds 타입에 따라 정수이면 fixedDelay 문자열이면 fixedDelayString

📋 fixedRate & fixedRateString


  • 이전 작업이 완료될 때까지 대기
  • 메서드 시작시간 기준, milliseconds 간격으로 실행
  • 모든 실행이 독립적인 경우에 유용
  • milliseconds 타입에 따라 정수이면 fixedRate 문자열이면 fixedRateString

📋 initialDelay & initialDelayString


  • 초기 지연 시간으로 최초 실행시에만 적용되는 지연 시간
  • fixedDelay 혹은 fixedRate 등의 고정 시간값과 함께 사용
  • initialDelay 시간 이후 최초 실행, 이후 fixedDelay 시간마다 실행
  • milliseconds 타입에 따라 정수이면 initialDelay 문자열이면 initialDelayString

📋 Cron & Zone


  • Cron 표현식을 통해 매 특정 시점마다 실행
    • Cron: "* * * * * *"
    • 초(0-59) 분(0-59) 시간(0-23) 일(1-31) 월(1-12) 요일(0-7)
  • Zone = "Asia/Seoul"
    • DefaultLocal 시간대 사용

📌 Test


import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component // Class에는 @Component 추가
@EnableAsync // Class에는 @EnableAsync 추가
public class ScheduleTest {

    /**
     * 이전 작업이 완료될 때까지 대기
     * 메서드 종료시간 기준, `milliseconds` 간격으로 실행
     * 하나의 인스턴스만 항상 실행되도록 해야 할 상황에서 유용
     */
    @Scheduled(fixedDelay = 1000)
    public void scheduledFixedDelayTest() throws InterruptedException {
        log.info("Fixed Delay Test: {}", System.currentTimeMillis() / 1000);
        Thread.sleep(5000);
    }

    // 문자열 milliseconds를 사용할 때
    @Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds}")
    public void scheduledFixedDelayStringTest() throws InterruptedException {
        log.info("Fixed Delay String Test: {}", System.currentTimeMillis() / 1000);
        Thread.sleep(5000);
    }
    
    
    /**
     * 이전 작업이 완료될 때까지 대기
     * 메서드 시작시간 기준, `milliseconds` 간격으로 실행
     * 모든 실행이 독립적인 경우에 유용
     */
    @Async // Method에는 @Async 추가
    @Scheduled(fixedRate = 1000)
    public void scheduledFixedRateTest() throws InterruptedException {
        log.info("Fixed Rate Test: {}", System.currentTimeMillis() / 1000);
        Thread.sleep(5000);
    }

    // 문자열 milliseconds를 사용할 때
    @Async // Method에는 @Async 추가
    @Scheduled(fixedRateString = "${fixedRate.in.milliseconds}")
    public void scheduledFixedRateStringTest() throws InterruptedException {
        log.info("Fixed Rate String Test: {}", System.currentTimeMillis() / 1000);
        Thread.sleep(5000);
    }


    /**
     * 초기 지연 시간으로 최초 실행시에만 적용되는 지연 시간
     * `fixedDelay` 혹은 `fixedRate` 등의 고정 시간값과 함께 사용
     * `initialDelay` 시간 이후 최초 실행, 이후 `fixedDelay` 시간마다 실행
     */
    // 1초 대기 후 메서드 종료시간 기준으로 5초마다 반복
    @Scheduled(fixedDelay = 5000, initialDelay = 1000)
    public void scheduledFixedDelayWithInitialDelayTest() {
        long now = System.currentTimeMillis() / 1000;
        log.info("Initial Delay with Fixed Delay Test: {}", now);
    }
    
    // 1초 대기 후 메서드 시작시간 기준으로 5초마다 반복
    @Scheduled(fixedRate = 5000, initialDelayString = "1000")
    public void scheduledFixedRateWithInitialDelayTest() {
        long now = System.currentTimeMillis() / 1000;
        log.info("Initial Delay with Fixed Rate Test: {}", now);
    }


    /**
     * `Cron` 표현식을 통해 매 특정 시점마다 실행
     * * `Cron`: `"* * * * * *"`
     * * 초(0-59) 분(0-59) 시간(0-23) 일(1-31) 월(1-12) 요일(0-7)
     * `Zone` = `"Asia/Seoul"`
     * * `Default`는 `Local` 시간대 사용
     */
    @Scheduled(cron = "0 15 10 15 * ?") // 매월 15일 오전 10시 15분 실행
    // @Scheduled(cron = "0 15 10 15 11 ?") // 11월 15일 오전 10시 15분 실행
    // @Scheduled(cron = "${cron.expression}")
    public void scheduledCronExpressionTest() {
        long now = System.currentTimeMillis() / 1000;
        log.info("Scheduled with Cron Expression Test: {}", now);
    }

    // 유럽/파리 시간 기준 매월 15일 오전 10시 15분 실행
    @Scheduled(cron = "0 15 10 15 * ?", zone = "Europe/Paris")
    public void scheduledCronExpressionWithZoneTest() {
        long now = System.currentTimeMillis() / 1000;
        log.info("Scheduled with Cron Expression and Zone Test: {}", now);
    }

}

📌 Reference


https://data-make.tistory.com/699

profile
꾸준히 노력하는 개발자

0개의 댓글