[Spring boot] Spring Scheduler 사용법

2022. 5. 26. 11:49spring boot

728x90
반응형

Spring Schecduler

 

리눅스의 cron 처럼 spring에도 일정 주기마다 메소드를 실행시킬 수 있는 Spring Schecduler 가 있다.


Dependency

spring boot starter 에 내장되어있다. 

import org.springframework.scheduling.annotation.EnableScheduling;

Enable

@EnableScheduling 어노테이션을 실행 클래스나 스케줄을 실행하는 메소드를 가지고 있는 클래스 상위에 추가 

@EnableScheduling //추가
@SpringBootApplication
public class SpringBatchTestApplication {

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

@Schduled 어노테이션은 일정 주기마다 실행할 메소드에 달아준다.

이때 해당 클래스는 스프링 빈에 등록 되어야한다. (@Component, @Service, @Conroller 중 하나 추가)

 

※ @Scheduled 규칙

  • 메소드 리턴값은 void
  • 매개변수 사용불가
package com.hsj.SpringBatchTest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class Scheduler {

    @Scheduled(fixedDelay = 1000) //옵션마다 이 메소드가 실행된다.
    public void schedulePing() {
        log.info("ping");
    }
}

@Scheduled 옵션

cron cron 표현식으로 실행 주기를 정한다.
zone 시간대 기준 나라를 설정한다.
fixedDelay 이전 작업이 종료된 후 설정 시간이 지나면 다시 시작한다.
fixedDelayString fixedDelay 와 동일하고 문자열로 시간을 설정한다
fixedRate - 정해진 시간마다 반복
- 이전 작업이 끝날때까지 대기한다
- 병렬 수행시 @Async를 추가한다.
fixedRateString fixedRate 과 동일하고 문자열로 시간을 설정한다
initialDelay 첫 실행 시 initialDelay 만큼 기다린 뒤 실행한다. 이후로는 fixedDelay 마다 반복 실행한다.
initialDelayString initialDelay 과 동일하고 문자열로 시간을 설정한다
timeUnit 시간 단위 설정, 기본값은 milliseconds 이다.
728x90
반응형

'spring boot' 카테고리의 다른 글

[Spring boot] Spring batch 개념정리  (0) 2022.05.27