민팽로그

[spring] scheduler - cron 본문

🍃spring boot

[spring] scheduler - cron

민팽 2021. 8. 24. 15:22

https://spring.io/guides/gs/scheduling-tasks/

 

Scheduling Tasks

this guide is designed to get you productive as quickly as possible and using the latest Spring project releases and techniques as recommended by the Spring team

spring.io

 

Scheduler

일정 주기마다 반복해서 주어진 작업 자동 실행

- @Scheduled 어노테이션을 사용하여 특정 메소드가 실행되는 시기, 주기를 설정함

 

cron

@Scheduled 옵션 중 하나. 초(0~59), 분(0~59), 시(0~23), 일(0~31), 월(1~12), 요일(0(일)~6(토))[, 연도] 순으로 주기를 설정할 수 있음

ex) * * 1 * * * : 매월 매일 1시 매분 매초마다 실행

*  모든 조건에서 실행 - 매 초, 매 분, 매 시간 등
/  특정 간격마다 실행 - 초 부분에 0/20 으로 표기하면 0초부터 시작하여 20초마다 실행
-  특정 조건에서 실행 - 시 부분에 21-23 으로 표기하면 21시부터 23시까지 실행

 

사용 예시

1. 스케줄러 클래스를 만든 후 @Component 어노테이션을 추가하여 스프링이 자동으로 생성 및 실행을 할 수 있도록 함

2. @Scheduled 어노테이션 옵션으로 cron 선택 -> 설정한 구체적인 주기에 맞춰 작업 실행

3. application 클래스에 @EnableScheduling 어노테이션을 추가하여 스프링이 스케줄링을 할 수 있도록 해줌

 

- Scheduler 클래스

@Component // 스프링이 필요 시 자동으로 생성하는 클래스 목록에 추가
public class Scheduler {

    // 초, 분, 시, 일, 월, 요일 순서
    @Scheduled(cron = "0 0 1 * * *")
    public void updatePrice() throws InterruptedException {
        //자동화 할 코드
        ...
        
        //과부하 방지를 위해 필요 시 sleep을 적절히 사용
            TimeUnit.SECONDS.sleep(1); //1초마다 쉼
            
        ...
    }
}

 

- Application 클래스

@EnableScheduling // 스프링 부트에서 스케줄러가 작동하게 함
@SpringBootApplication
public class Application {

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

 

Comments