본문 바로가기

IT/Spring

[Spring Boot] 간단하게 @Scheduled 사용하기

1. @Scheduled 어노테이션

특정 메소드에 @Scheduled 어노테이션을 선언하면 설정한 값에 따라 주기적으로 해당 메소드를 실행시킬 수 있습니다.

 

2. @Scheduled 사용 방법 

1) 스프링 스케줄링 기능 활성화

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

@SpringBootApplication
@EnableScheduling
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

}
@SpringBootApplication이 선언된 곳에 @EnableScheduling 어노테이션을 추가해 스프링 스케줄링 기능을 활성화시킵니다.

 

2) 스케줄 등록

import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class BatchScheduler {
    
    Logger logger = LoggerFactory.getLogger(this.getClass());
    
    //10초마다 실행
    @Scheduled(cron = "0/10 * * * * *")
    public void testSchedule() {
        
        logger.info("[MYTEST] test batch {}", LocalDateTime.now());
        
    }
    
}
BatchScheduler 클래스를 생성하고 컴포넌트로 등록합니다.
그리고 메소드 위에 @Scheduled 어노테이션을 선언하면 스케줄에 등록되고 설정한 시간마다 실행되게 됩니다.

 

@Scheduled 옵션

fixedDelay 이전 작업이 종료된 후 설정 시간만큼 기다린 후에 시작한다. (밀리세컨드)
@Scheduled(fixedDelay = 1000)
fixedRate 이전 작업이 종료되지 않아도 설정된 시간마다 시작한다. (밀리세컨드)
@Scheduled(fixedRate = 1000)
initialDelay 작업 시작 시, 설정된 시간만큼 기다린 후 시작한다. (밀리세컨드)
@Scheduled(fixedRate = 1000, initialDelay = 2000)
cron 원하는 시간대를 설정하여 작업을 실행한다.
@Scheduled(cron = "* * * * * *") 
(초(0-59), 분(0-59), 시간(0-23), 일(1-31), 월(1-12), 요일(1-7, 1:일, 7:토))

zone 시간대를 설정 한다. 미설정 시 로컬 시간대가 적용된다.
@Scheduled(cron = "* * * * * *", zone = "Asia/Seoul") 

 

3) cron 예제

cron 값에 특수문자를 추가해서 다양한 기간을 설정할 수 있습니다.

* : 모든 값 
? : 설정 없음
, : 배열 설정 ex) 1,3,5
- : 범위 설정 ex) 3-5
/ : 특정 값을 기준으로 특정값 마다 반복 

0 0 0 * * * : 매일 00시 00분 00초에 실행
0 0 2 * * MON : 월요일 새벽 2시에 실행
0/30 * * * * ? : 30초 마다 실행