[Spring] @Scheduled 스프링 스케쥴러

2021. 3. 10. 15:44Spring

 

* 일정 주기마다 자동으로 실행하는 스케쥴러*

 

 

 

▶ @Scheduled Spring 3.1 이상부터 지원

일정시간에 주기적으로 호출해야하는 메소드가 있을 때 Spring에서 지원해주는 @Schedueled 어노테이션을 사용하면 간단하게 구현이 가능하다.

 

 

 

▶ @Scheduled 어노테이션의 속성

  • cron : "초/분/시/일/월/요일(/년)"를 표현해서 사용

  • zone : cron표현식을 사용했을 때 사용할 time zone을 따로 설정하지 않으면 기본적으로 서버의 time zone을 사용
  • fixedDelay : milliseconds 단위로, 이전 작업이 끝난 시점으로부터 고정된 시간을 설정
  • fixedDelayString : fixedDelay와 기능적으로 같은 옵션이지만 property의 value만 문자열로 넣은것
    ex) fixedDelay = 3000,    fixedDelayString = "3000"
  • fixedRate : milliseconds 단위로, 이전 작업이 수행되기 시작한 시점으로부터 고정된 시간을 설정
  • fixedRateString : fixedRate와 기능적으로 같은 옵션이지만 property의 value만 문자열로 넣은것
  • initialDelay : 스케줄러에서 메서드가 등록되자마자 수행하는것이 아닌 초기 지연시간을 설정
  • initialDelayString : initialDelay와 기능적으로 같은 옵션이지만 property의 value만 문자열로 넣은것

 

 

설정 & 예시)

1) application-dev.yml 

spring:
    
    task: 
      scheduling: 
        pool: 
          size: 8 
        thread-name-prefix: my-scheduler

2) Controller.java

 -1) 클래스에 어노테이션 설정

 @EnableScheduling

@SpringBootApllication

@EnableScheduling
@SpringBootApplication
public class VacantController extends RootController{

.
.
.

//			초/분/시/일/월/요일
	@Scheduled(cron = "0 0 0 1 * *") 		
	private void vacantCopyEveryMonth() { 
		vacantService.vacantCopyEveryMonth();
	}
}

 -2) 스케쥴러를 사용할 하위 메소드에 @Scheduled 어노테이션 설정

//     초/분/시/일/월/요일
@Scheduled(cron = "0 0 0 1 * *") 
private void vacantCopyEveryMonth() { 
	vacantService.vacantCopyEveryMonth();
}

 

=> 매월 1일 정각에 실행

 

 

▶ cron 설정

 

(cron = "* * * * * *")

- 초/분/시/일/월/요일/년도(옵션)

 

 -초 0-59 , - * / 

 -분 0-59 , - * / 

 -시 0-23 , - * / 

 -일 1-31 , - * ? / L W

 -월 1-12 or JAN-DEC , - * / 

 -요일 1-7 or SUN-SAT , - * ? / L # (1:일, 2:월, 3:화, 4:수, 5:목, 6:금, 7:토)

 -년(옵션) 1970-2099 , - * /

 

* : 모든 값

? : 특정 값 없음

- : 범위 지정에 사용

, : 여러 값 지정 구분에 사용

/ : 초기값과 증가치 설정에 사용

L : 지정할 수 있는 범위의 마지막 값

W : 월~금요일 또는 가장 가까운 월/금요일

# : 몇 번째 무슨 요일 2#1 => 첫 번째 월요일

 

 

 

'Spring' 카테고리의 다른 글

MVC패턴 이해하기1  (0) 2022.10.25
MVC패턴의 등장  (0) 2022.10.25
DispatchServlet을 통해 보는 스프링 구조  (0) 2022.09.02
[Spring] - 414 request-uri too large  (0) 2021.03.22
[Srping] 전자정부프레임워크 - mariadb 연결  (0) 2021.03.16