(5) Spring Official Guide - Scheduling Tasks

HEYDAY7·2022년 10월 26일
0

Learn Kotlin + Spring

목록 보기
6/25

Scheduling Tasks

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

한줄 요약

정말 간단하게 Spring 환경에서 스케쥴링의 기본, 즉 주기적으로 함수를 호출하는 방법에 대해 익힌다.

프로젝트 구성

Spring initializer를 통해 다른 dependency 없이 프로젝트를 만들고, gradle 파일에 아래 library 딱 하나만 추가해주자
testImplementation("org.awaitility:awaitility:3.1.2")

Create a Scheduled Task

@Component
class ScheduledTasks {
    val log: Logger = LoggerFactory.getLogger(ScheduledTasks::class.java)
    val dateFormat = SimpleDateFormat("HH:mm:ss")

    @Scheduled(fixedRate = 5000)
    fun reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(Date()))
    }
}

코드 자체는 매우 간단하다. 핵심만 집자면
@Scheduled annotation을 통해서 해당 함수를 주기적으로 반복하며, 반복 주기는 [fixed Rate, fixed Delay, cron] 셋 중 하나로 구성해야야 한다는 것이다.

Enable Scheduling

@Scheduled annotation이 동작하게 하려면 여러 방식이 있겠지만 가장 간단한 방식은 상위에서 @EnableScheduling annotation을 넣는 것이다. 따라서 Application class에다가 해당 annotation을 달고 실행하면 주기적으로 찍히는 log를 확인할 수 있다.

마무리

사실 좀 더 Job Scheduling에 관한 이야기가 나올 거라고 생각했는데, 기초 중에 기초였다. 뭐 후에 좀 더 자세한 내용이 나오지 않을까 생각한다.
코드는 여기서 볼 수 있다.

profile
(전) Junior Android Developer (현) Backend 이직 준비생

0개의 댓글