@Scheduled 어노테이션

스프링 공부

목록 보기
24/35

📌 @Scheduled 어노테이션 개요

@ScheduledSpring Framework에서 일정한 주기로 특정 메서드를 실행하도록 하는 어노테이션입니다.
스케줄링을 활성화하면 별도의 쓰레드에서 작업을 수행하므로, 주기적인 작업을 실행할 때 유용합니다.


1. 기본 사용법 (@EnableScheduling 필수)

먼저, @Scheduled을 사용하려면 스케줄링을 활성화해야 합니다.

🔹 스케줄링 활성화 (@EnableScheduling)

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling  // 스케줄링 기능 활성화
public class SchedulerConfig {
}

이제 @Scheduled를 사용할 준비가 되었습니다.


2. @Scheduled 주기 설정 방법

@Scheduled는 3가지 방식으로 실행 주기를 설정할 수 있습니다.

✅ 1) fixedRate (고정 주기 실행)

  • 이전 작업이 끝나는 것을 기다리지 않고, 무조건 일정한 주기로 실행
  • 단위: 밀리초(ms)
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTask {

    @Scheduled(fixedRate = 5000) // 5초마다 실행
    public void runTask() {
        System.out.println("fixedRate 실행: " + System.currentTimeMillis());
    }
}

특징: 이전 작업이 끝나지 않았어도 일정 시간 간격으로 실행됨.


✅ 2) fixedDelay (이전 작업이 끝난 후 일정 시간 뒤 실행)

  • 이전 작업이 완료된 후, 일정 시간 뒤에 실행됨.
  • 단위: 밀리초(ms)
@Scheduled(fixedDelay = 5000) // 이전 작업 종료 후 5초 뒤 실행
public void runTask() {
    System.out.println("fixedDelay 실행: " + System.currentTimeMillis());
}

특징: 이전 작업이 끝난 후 일정 시간 기다린 후 실행됨.


✅ 3) cron 표현식 (정해진 시각에 실행)

  • 리눅스 크론(Cron) 표현식을 사용하여 정교한 주기 설정 가능
@Scheduled(cron = "0 0 12 * * ?") // 매일 정오(12:00)에 실행
public void runTask() {
    System.out.println("cron 실행: " + System.currentTimeMillis());
}

특징: 특정 요일, 날짜, 시간 단위로 정밀한 설정이 가능함.


3. cron 표현식 설명

필드의미예시
초(0-59)실행할 초0, 15, 30
분(0-59)실행할 분0, 15, 30
시(0-23)실행할 시0, 12, 23
일(1-31)실행할 날짜1, 15, * (매일)
월(1-12)실행할 월1, 6, * (매월)
요일(0-7)실행할 요일 (0,7=일요일)0, 5, * (매일)

🔹 자주 사용하는 cron 예시
| 표현식 | 실행 주기 |
|--------|---------|
| 0 * * * * ? | 매 분마다 실행 |
| 0 0 12 * * ? | 매일 12:00(정오)에 실행 |
| 0 0 0 * * MON | 매주 월요일 00:00에 실행 |
| 0 0 9-17 * * ? | 매일 9시~17시까지 매시간 실행 |


4. @Scheduled의 주의점

  1. 메서드는 void이고, 매개변수를 가지지 않아야 함
    @Scheduled(fixedRate = 5000)
    public void runTask(int param) {  // ❌ 매개변수 사용 불가
        System.out.println("잘못된 사용 예시");
    }
  2. 스케줄링은 기본적으로 단일 쓰레드에서 실행됨
    • 여러 개의 스케줄링 작업을 병렬로 실행하려면 @Async를 함께 사용해야 함.
  3. JVM이 종료되면 스케줄링도 종료됨
    • Spring Boot에서 백그라운드 작업으로 실행하려면 별도 설정 필요

5. @Scheduled + @Async (비동기 스케줄링)

기본적으로 @Scheduled싱글 쓰레드에서 실행되므로, 실행 시간이 긴 작업이 있으면 비동기 실행하는 것이 좋습니다.

🔹 비동기 실행 설정

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

@Component
public class AsyncScheduledTask {

    @Async  // 비동기 실행
    @Scheduled(fixedRate = 5000)
    public void runTask() {
        System.out.println("비동기 fixedRate 실행: " + System.currentTimeMillis());
    }
}

📢 비동기 실행을 사용하려면 @EnableAsync를 설정해야 합니다.

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@Configuration
@EnableAsync  // 비동기 실행 활성화
public class AsyncConfig {
}

✅ 정리

설정 방식실행 방식
fixedRate = 5000이전 작업이 끝나지 않아도 5초마다 실행
fixedDelay = 5000이전 작업이 끝난 후 5초 뒤 실행
cron = "0 0 12 * * ?"매일 정오(12:00)에 실행
@Async + @Scheduled비동기 스케줄링으로 실행

정기적인 작업(배치, 캐시 갱신, 로그 처리 등)에 유용
멀티스레드 환경에서는 @Async와 함께 사용 고려

추가로 궁금한 점이 있으시면 질문 주세요! 😊🚀

profile
AI 답변 글을 주로 올립니다.

0개의 댓글