TIL

24.07.31 TIL - @Scheduled 관련

개발공명 2024. 7. 31. 23:45

 

오늘 배운 것

  • @Scheduled
  • @EnableScheduling

 

@Scheduled란?

특정 코드를 주기적으로 또는 특정 시간에 반복 실행하고자 할 때 사용하는 Spring Framework에서 제공하는 annotation.

 

이 annotation으로 간단하게 반복적, 주기적으로 실행해야 하는 작업을 별도 scheduler 설정 없이도 할 수 있다. 

 

예를 들어 '매일 새벽 1시에 제품 가격을 갱신하는 로직 수행해야지' 또는 '30분마다 알림 보내는 로직 수행해야지' 이렇게 구현하고 싶을 때 쉽게 할 수 있도록 도와주는 것이다. 

 

 

@Scheduled 주요 속성

  • cron : CronExpression을 사용해 작업이 실행될 주기를 간단하게 지정하는 것이다. 
@Scheduled(cron = "0 0 * * * *")

 

  • fixedDelay : 이전 작업이 끝난 후 대기할 시간을 지정하는 것이다.
                         지정한 대기 시간 이후 작업이 다시 실행된다.
                         이때 대기 시간은 ms 단위 (1000ms = 1s )이다. 
@Scheduled(fixedDelay = 5000)

 

  • fixedRate : 이전 작업이 시작된 시점부터 대기할 시간을 지정하는 것이다. 
                        fixedDelay와 유사하지만 작업 끝난 시점인지 시작 시점인지 차이다. 
                        역시 마찬가지로 대기 시간은 ms 단위이다.
@Scheduled(fixedRate = 5000

 

  • initialDelay : 작업 처음 시작하기 전에 대기할 시간을 지정하는 것이다. 
                           애플리케이션 시작 후 대기 시간 후에 처음 작업 시작하는 것이다. 
                           fixedDelay, fixedRate와 같이 사용할 수 있다. 
                           역시 마찬가지로 대기 시간은 ms 단위이다. 
// 애플리케이션 시작 10초 후 첫 작업 실행
// 이후 5초마다 작업 실행
@Scheduled(initialDelay = 10000, fixedRate = 5000)

 

@Scheduled 사용 예시 

아래 코드처럼 사용하는 것이다. 

아래 코드는 10초마다 console에 출력하는 작업을 @Scheduled를 사용해 구현한 것이다. 

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyScheduledTask {

    @Scheduled(fixedRate = 10000)
    public void performTask() {
        System.out.println("Scheduled Task!");
    }
}

 

 

@Scheduled 사용 시 주의 사항 및 @EnableScheduling

 

@Scheduled 사용 시 주의 사항

@Scheduled를 사용해 Scheduler를 만들 때 Schdeduler를 구현한 클래스가 스프링 빈에 등록된 클래스여야 합니다. 

 

@Component annotation이 있는 클래스여야 합니다. 

 

 @EnableScheduling

그리고 @Scheduled를 사용하기 위해서는 Application 클래스에 @EnableScheduling annotation을 붙여줘야 합니다. 

 

Application 클래스는 @SpringBootApplication annotation이 붙어있는 클래스main 메서드가 있는 클래스입니다. 

 

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

@SpringBootApplication
@EnableScheduling
public class MyApplication {

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

 

 

더 알아보면 좋을 것

CronExpression에 대해서 상세히 적지 못햇지만 더 알아보면 좋을 것 같다. 

 

 

참고 자료 및 잘 설명된 블로그

https://docs.spring.io/spring-framework/reference/integration/scheduling.html#scheduling-enable-annotation-support

 

Task Execution and Scheduling :: Spring Framework

All Spring cron expressions have to conform to the same format, whether you are using them in @Scheduled annotations, task:scheduled-tasks elements, or someplace else. A well-formed cron expression, such as * * * * * *, consists of six space-separated time

docs.spring.io

 

https://dev-coco.tistory.com/176

 

[Spring Boot] @Scheduled을 이용해 일정 시간 마다 코드 실행하기

@Scheduled Spring Boot에서 @Scheduled 어노테이션을 사용하면 일정한 시간 간격으로, 혹은 특정 시간에 코드가 실행되도록 설정할 수 있다. 주기적으로 실행해야 하는 작업이 있을 때 적용해 쉽게 사용

dev-coco.tistory.com

 

https://velog.io/@developer_khj/Spring-Boot-Scheduler-Scheduled

 

[Spring Boot] @Scheduled를 이용한 스케쥴러 구현하기

Spring Boot`에서 @Scheduled 어노테이션을 이용하여 스케쥴러를 구현하는 방법에 대해 작성하였습니다

velog.io