TY blog

Spring 쿼츠 라이브러리 본문

프로그래밍 언어/Spring Framework

Spring 쿼츠 라이브러리

주짓수하는 개발자 2024. 2. 9. 17:12
Spring Quartz 라이브러리

 

일반적으로 스케줄러를 구성하기 위해 사용하며 주기적으로 특정한 시간대에 

프로그램 실행하고 싶은 경우에 사용합니다. 

 

1. Spring Dependency 추가하기
<!-- pom.xml을 이용하는 경우 -->
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.2</version> 
</dependency>
/* Gradle을 이용하는 경우 */
dependencies {
    implementation 'org.quartz-scheduler:quartz:2.3.2' 
}
2. @EnableScheduling

 

스프링 애플리케이션에 스케줄링 기능을 활성화하는 어노테이션, Bean을 등록하는 config 설정파일이나 Spring boot 실행파일에 추가해 준다. 

 

3. @Scheduled 

 

구현한 로직을 정기적으로 실행하기 위해 사용하는 어노테이션, 지정된 일정에 따라 주기적으로 실행이 된다.

/* 매 0초 마다 실행 지정 */
@Scheduled(cron="0 * * * * * ")

/* Asia/Seoul 시간을 기준으로 매 0초 마다 실행 지정, 
zone 값을 지정하지 않을 시 서버 시간대로 설정 */
@Scheduled(cron="0 * * * * * ", zone="Asia/Seoul")

/* 함수 시작 후 5초 간격으로 실행 */
@Scheduled(fixedRate = 5000) 

/* 함수 종료 후 5초 간격으로 실행 */
@Scheduled(fixedDelay = 5000)

 

 4. cron 표현식 

 

스케줄러의 정규 표현식으로 사용자가 표현식을 사용해서 특정 주기를 지정할 수 있다. 

cron = seconds(0~59), minutes(0~59), hours(0~23), day(1~31), month(1~12), day of week(1~7), year(optional)

 

표현식 예시
매 시간의 15분과 45분에 실행 cron= "15, 45 * * * *"
30분마다 실행(즉, 매 시간 30분과 0분에 실행) cron="*/30 * * * *"
매 5분마다 실행(즉, 0분, 5분, 10분, 등) cron="*/5 * * * *"

 

 

5. Quartz Test
@SpringBootApplication
@EnableScheduling
public class SpringProfileV2Application {

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

    @Scheduled(fixedRate = 5000) // 서비스 시작 후 5초마다 실행
    public void scheduledTask() {
        System.out.println("Scheduled Task is running...");
    }

}

 

 

 

Comments