@Scheduled 어노테이션 개요@Scheduled은 Spring Framework에서 일정한 주기로 특정 메서드를 실행하도록 하는 어노테이션입니다.
스케줄링을 활성화하면 별도의 쓰레드에서 작업을 수행하므로, 주기적인 작업을 실행할 때 유용합니다.
@EnableScheduling 필수)먼저, @Scheduled을 사용하려면 스케줄링을 활성화해야 합니다.
@EnableScheduling)import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling // 스케줄링 기능 활성화
public class SchedulerConfig {
}
이제 @Scheduled를 사용할 준비가 되었습니다.
@Scheduled 주기 설정 방법@Scheduled는 3가지 방식으로 실행 주기를 설정할 수 있습니다.
fixedRate (고정 주기 실행)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());
}
}
✔ 특징: 이전 작업이 끝나지 않았어도 일정 시간 간격으로 실행됨.
fixedDelay (이전 작업이 끝난 후 일정 시간 뒤 실행)@Scheduled(fixedDelay = 5000) // 이전 작업 종료 후 5초 뒤 실행
public void runTask() {
System.out.println("fixedDelay 실행: " + System.currentTimeMillis());
}
✔ 특징: 이전 작업이 끝난 후 일정 시간 기다린 후 실행됨.
cron 표현식 (정해진 시각에 실행)@Scheduled(cron = "0 0 12 * * ?") // 매일 정오(12:00)에 실행
public void runTask() {
System.out.println("cron 실행: " + System.currentTimeMillis());
}
✔ 특징: 특정 요일, 날짜, 시간 단위로 정밀한 설정이 가능함.
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시까지 매시간 실행 |
@Scheduled의 주의점void이고, 매개변수를 가지지 않아야 함@Scheduled(fixedRate = 5000)
public void runTask(int param) { // ❌ 매개변수 사용 불가
System.out.println("잘못된 사용 예시");
}@Async를 함께 사용해야 함.@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와 함께 사용 고려
추가로 궁금한 점이 있으시면 질문 주세요! 😊🚀