스프링부트에서 스케줄링은 정해진 주기마다 특정 작업을 자동으로 실행하는 기능을 제공한다. 이 기능을 통해 주기적인 데이터 처리나 백그라운드 작업을 수행할 수 있다. 예를 들면, 매일 자정에 데이터 백업을 수행하거나, 일정 간격마다 외부 API를 호출하는 작업을 자동화할 수 있다.
스프링부트에서는 스케줄러 기능을 @Scheduled 어노테이션을 사용해 쉽게 구현할 수 있다.
1. @EnableScheduling 어노테이션 활성화:
스케줄러를 사용하려면 스프링 부트 애플리케이션의 메인 클래스나 설정 클래스에 @EnableScheduling 어노테이션을 추가해야 한다.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling // 스케줄링 기능 활성화
public class SchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulerApplication.class, args);
}
}
2. 스케줄 작업 정의하기:
스케줄 작업을 수행할 메서드에 @Scheduled 어노테이션을 추가한다.
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
public class ScheduledTasks {
// 매 5초마다 실행되는 작업
@Scheduled(fixedRate = 5000)
public void fixedRateTask() {
System.out.println("Fixed Rate Task: " + LocalDateTime.now());
}
// 이전 작업이 끝난 후 5초 후에 실행
@Scheduled(fixedDelay = 5000)
public void fixedDelayTask() {
System.out.println("Fixed Delay Task: " + LocalDateTime.now());
}
// 매일 자정(00:00:00)에 실행
@Scheduled(cron = "0 0 0 * * ?")
public void cronTask() {
System.out.println("Cron Task: " + LocalDateTime.now());
}
}
1. fixedRate
@Scheduled(fixedRate = 5000) // 5초마다 실행
public void fixedRateTask() {
System.out.println("Fixed Rate Task: " + LocalDateTime.now());
}
2. fixedDelay
fixedDelay가 설정되면, 7초마다 실행된다.@Scheduled(fixedDelay = 5000) // 이전 작업 종료 후 5초 후 실행
public void fixedDelayTask() {
System.out.println("Fixed Delay Task: " + LocalDateTime.now());
}
3. cron 표현식
@Scheduled(cron = "0 0 0 * * ?") // 매일 자정 실행
public void cronTask() {
System.out.println("Cron Task: " + LocalDateTime.now());
}
예시 크론 표현식:
"0 0 12 * *" -> 매일 정오 12시에 실행"0 15 10 * *" -> 매일 오전 10시 15분에 실행"0 0/5 * * *" -> 매 5분마다 실행멀티 스레드 환경:
기본적으로 스케줄링은 단일 스레드에서 동작한다. 여러 스케줄이 동시에 실행될 수 있으면 @Async와 @ThreadPoolTaskScheduler를 사용해 멀티 스레드 환경을 구성할 수 있다.
스케줄링 예외 처리:
스케줄러에서 발생하는 예외는 처리하지 않으면 작업이 중지될 수 있다. 예외 발생 시 로그를 남기거나 필요한 처리를 해주는 것이 좋다.
@Scheduled(fixedRate = 5000)
public void safeTask() {
try {
// 스케줄링 작업
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
@EnableAsync와 @Async를 조합해 사용할 수 있다.import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncTasks {
@Async
public void runAsyncTask() {
System.out.println("Executing Async Task");
}
}
스케줄링 작업은 서버가 실행된 후 자동으로 주기적으로 실행된다. 테스트를 위해 작업 내에서 로그 출력이나 파일 생성을 추가할 수 있다.
스프링부트 스케줄러는 정기적으로 반복되는 작업을 자동화하는 데 유용하다. 주로 데이터 백업, 이메일 발송, API 호출 등 다양한 작업에 사용된다.
@Secheduled를 이용해 쉽게 구현할 수 있으며, fixedRate, fixedDelay, cron 등 다양한 방식을 지원한다.
추가적으로, 멀티 스레드 환경 설정과 예외 처리를 통해 스케줄링의 안전성을 높일 수 있다.