@Scheduled
특정 메서드에 @Scheduled 어노테이션을 선언하면 설정한 값에 따라 주기적으로나 특정 시간이나 기간에 해당 메서드를 실행시킬 수 있다. Spring Scheduler는 별도의 추가적인 의존성이 필요하지 않다. Spring Boot starter에 기본적인 의존성으로 제공된다. 사용하기 위해서는 @EnableScheduling 어노테이션을 붙여주면 된다.
1. Scheduling 기능 활성화 @SpringBootApplication이 선언된 곳에 @EnableScheduling 어노테이션을 추가해 스프링 스케줄링 기능을 활성화시킨다.
package com.example.bitmovie;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling
@SpringBootApplication
@EnableScheduling //스케줄링 기능 활성화
public class BitmovieApplication implements Jackson2ObjectMapperBuilderCustomizer {
public static void main(String[] args) {
SpringApplication.run(BitmovieApplication.class, args);
}
}
이런 설정을 잡아 준 후 실제 사용은 아래와 같이 사용할 수 있다. @Scheduled 어노테이션 메서드에 붙여 주기만 하면 된다. 해당 어노테이션의 내부 값으로 scheduler가 실행 될 타이밍을 정할 수 있다. scheduling을 할 메서드는 2개의 조건을 가진다.
A. method는 void의 return 타입을 가져야한다.
B. method는 파라미터를 가질 수 없다.
2. Scheduled 등록
BatchScheduler 클래스를 생성하고 컴포넌트로 등록한다. 그리고 메서드 위에 @Scheduled 어노테이션을 선언하면 스케줄에 등록되고 설정한 시간마다 실행되게 된다.
package data.util;
import data.service.user.CouponService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@RequiredArgsConstructor
public class BatchScheduler {
private final CouponService couponService;
//생일 쿠폰 발급
@Scheduled(cron = "0 0 0 * * *", zone = "Asia/Seoul") //매일 자정 실행
public void insertBirthCoupon () {
couponService.insertBirthCoupon();
}
}
Final Project 기준 Util(package) → BatchScheduler 클래스
@Scheduled 옵션
fixedDelay | 이전 작업이 종료된 후 설정 시간만큼 기다린 후에 시작한다. (밀리세컨드) @Scheduled(fixedDelay = 1000) |
fixedRate | 이전 작업이 종료되지 않아도 설정된 시간마다 시작한다. (밀리세컨드) @Scheduled(fixedRate = 1000) |
initialDelay | 작업 시작 시, 설정된 시간만큼 기다린 후 시작한다. (밀리세컨드) @Scheduled(fixedRate = 1000, initialDelay = 2000) |
cron | 원하는 시간대를 설정하여 작업을 실행한다. @Scheduled(cron = "* * * * * *") (초(0-59), 분(0-59), 시간(0-23), 일(1-31), 월(1-12), 요일(1-7, 1:일, 7:토)) |
zone | 시간대를 설정 한다. 미설정 시 로컬 시간대가 적용된다. @Scheduled(cron = "* * * * * *", zone = "Asia/Seoul") |
cron 값에 특수문자를 추가해서 다양한 기간을 설정할 수 있다.
*: 모든 값
? : 설정 없음
, : 배열 설정 ex) 1,3,5
/ : 특정 값을 기준으로 특정값 마다 반복
0 0 0 * * * : 매일 00시 00분 00초에 실행
0 0 2 * * MON : 월요일 새벽 2시에 실행
0/30 * * * * ? : 30초 마다 실행
'SpringBoot' 카테고리의 다른 글
[SpringBoot][React] coolSMS 휴대전화 인증 (0) | 2022.11.21 |
---|