Spring Boot에서 @Scheduled를 이용한 정기 작업 구현

Spring Boot의 @Scheduled 어노테이션을 사용하면 정기적으로 실행해야 하는 작업을 손쉽게 구현할 수 있습니다.

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@EnableScheduling
public class UserLevelProcessor {
    
    private final SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss");
    
    /* 100초마다 실행 */
    @Scheduled(fixedRate = 100000)
    public void executePeriodicTask() {
        System.out.println("정기 작업 실행: executePeriodicTask");
    }
    
    /* 최초 10초 후 시작, 이후 완료 후 2초 간격으로 실행 */
    @Scheduled(initialDelay = 10000, fixedDelay = 2000)
    public void executeDelayedTask() {
        System.out.println("지연 작업 실행 시간: " + timeFormatter.format(new Date()));
    }

    /* 매일 15시 39분 0초에 실행 */
    @Scheduled(cron = "0 39 15 * * ?")
    public void executeCronTask() {
        System.out.println("크론 작업 현재 시간: " + timeFormatter.format(new Date()));
    }
}

여기서 주의할 점은 fixedRatefixedDelay의 실행 시점 차이입니다. 메서드 실행 시간이 길 경우 이 차이가 명확하게 드러납니다.

  • fixedRate: 이전 작업 시작 시점을 기준으로 다음 작업 예약
  • fixedDelay: 이전 작업 종료 시점을 기준으로 다음 작업 예약

실행 주기나 크론 표현식을 외부 설정 파일에서 관리할 수도 있습니다.

@Scheduled(fixedDelayString = "${task.delay.duration}")
public void loadConfigurationTask() {
    System.out.println("설정 기반 작업 실행, 시간: " + timeFormatter.format(new Date()));
}

자주 사용하는 Cron 표현식 예제

0 10,14,16 * * ?           오전 10시, 오후 2시, 4시에 실행
0/30 9-17 * * ?            오전 9시부터 오후 5시까지 30분마다 실행
0 12 ? * WED               매주 수요일 정오에 실행
0 0 12 * * ?               매일 오후 12시에 실행
0 * 14 * * ?               매일 오후 2시부터 2시 59분까지 1분마다 실행
0 0/5 14 * * ?             오후 2시부터 2시 55분까지 5분마다 실행
0 0/5 14,18 * * ?          오후 2시~2시 55분, 6시~6시 55분 사이 5분마다 실행
0 0-5 14 * * ?             오후 2시부터 2시 5분까지 1분마다 실행
0 10,44 14 ? 3 WED         3월 매주 수요일 오후 2시 10분, 2시 44분에 실행
0 15 10 ? * MON-FRI        월요일부터 금요일까지 오전 10시 15분에 실행
0 15 10 15 * ?             매월 15일 오전 10시 15분에 실행
0 15 10 L * ?              매월 마지막 날 오전 10시 15분에 실행
0 15 10 ? * 6L             매월 마지막 금요일 오전 10시 15분에 실행
0 15 10 ? * 6L 2002-2005   2002~2005년 매월 마지막 금요일 오전 10시 15분에 실행
0 15 10 ? * 6#3            매월 세 번째 금요일 오전 10시 15분에 실행
0 15 10 ? * *              매일 오전 10시 15분에 실행
0 15 10 * * ?              매일 오전 10시 15분에 실행
0 15 10 * * ? *            매일 오전 10시 15분에 실행
0 15 10 * * ? 2005         2005년 매일 오전 10시 15분에 실행

Cron 표현식 생성 도구

태그: spring-boot scheduled-tasks cron-expression java-spring

7월 1일 18:23에 게시됨