스프링개발자/201 - 일반

20. @Scheduled 어노테이션

2ndPrince 2020. 10. 17. 04:40

1. 개요

Cron Job처럼, 주기적으로 실행해야되는 action들을, 스프링 레벨에서 구현 할 수 있다.

(본 예제는 기존에 진행하던 코드를 포함하고있습니다)

2. 스프링 설정

@EnableScheduling 어노테이션을 Configuration 레벨에 추가한다.

package com.example.monorepo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableFeignClients
@EnableScheduling
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

 

3. 스케쥴 메소드 구현

fixedRate, fixedDelay, initialDelay 등등 여러 속성을 어노테이션 안에 제공할 수 있다.

10초마다 cleanDatabase라는 메소드가 호출된다.

아래 주석처리된 샘플처럼, 오늘 날짜부터 7일 이상된 로그 기록은 자동삭제하는 응용사례가 있다.

정해진 시간마다 어플리케이션의 smoke test를 실행하고, 그 결과를 slack notification으로 보낼 수도 있다.

package com.example.monorepo.service;

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

@Service
@Slf4j
public class NotificationService {

    private static final long TEN_SECONDS = 10000L;

    @Scheduled(fixedRate = TEN_SECONDS)
    public void cleanDatabase(){
        // [Sample Example]
        // ZonedDateTime now = ZonedDateTime.now();
        // int deleteCount = sampleRepository.deleteAllByTimestamp(now.minusDays(7));
        int deleteCount = 3;
        log.warn("{} number of old logs have been deleted by a scheduled service", deleteCount);
    }
}

 

4. 테스트

43초와 53초에 10초 간격으로 scheduled method가 실행되었다.

2020-10-16 15:28:43.864  WARN 19672 --- [   scheduling-1] c.e.m.service.NotificationService        : 3 number of old logs have been deleted by a scheduled service
2020-10-16 15:28:53.862  WARN 19672 --- [   scheduling-1] c.e.m.service.NotificationService        : 3 number of old logs have been deleted by a scheduled service

 

소스코드

github.com/2ndPrince/monorepo/tree/scheduled-annotation