Spring/Spring 문법

@Scheduler 사용해보기(주기 마다 메서드 실행)

열심히 해 2024. 12. 9. 17:33

SpringBoot 에서 @Scheduler 에노테이션을 사용하면 주기마다 특정 메서드를 호출할 수 있습니다.

 

1초 마다 로그 찍기

 

 

 

1. @EnableScheduling 에노테이션 추가하기

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

 

보통 @SpringBootApplication이 포함된 클래스에 추가합니다.

 

 

 

2. Bean 으로 등록된 클래스의 메서드에 @Scheduled 추가하기

@Scheduled(fixedDelay = 1000L)
public void schedulingTest() {
    LocalDateTime now = LocalDateTime.now();
    System.out.println("현재 시각:" + now);
}

@Scheduled(fixedRate = 1000L)
public void schedulingTest() {
    LocalDateTime now = LocalDateTime.now();
    System.out.println("현재 시각:" + now);
}

- 1초 마다 시각 찍기

 

 

@Scheduled(cron = "0 0 0 * * *")
@Transactional
public void cleanUpDailyVisitors() {
    List<Board> boards = boardRepository.findAll();

    for (Board board : boards) {
        board.clear(board.getVisitorCount());
    }

    System.out.println("하루 방문자 수가 초기화되었습니다.");
}

- 하루 방문자 수 초기화

 

 

3. fixedDelay, fixedRate, cron

  • fixedDelay: milliseconds 단위로, Task가 종료된 시점부터 정의된 시간만큼 지난 후 다시 Task를 실행합니다.
  • fixedRate: milliseconds 단위로, 이전 Task가 시작한 시점으로부터 정의된 시간만큼 지난 후 다시 Task를 실행합니다.
  • cron: 
    • 첫 번째 0: 초 (0초)
    • 두 번째 0: 분 (0분)
    • 세 번째 0: 시 (0시)
    • 네 번째 *: 일 (매일)
    • 다섯 번째 *: 월 (매월)
    • 여섯 번째 *: 요일 (매일)

 

4. fixedDelay   VS   fixedRate

 

@Scheduled(fixedDelay = 1000)
public void schedulingTest() throws InterruptedException {
    LocalDateTime now = LocalDateTime.now();
    System.out.println("현재 시각:" + now);
    Thread.sleep(5000);
}

 

-> '종료된 시점' 부터 계산하여 6초(메서드 안에서 5초 + 메스드 종료 후 1초)마다 1회 실행됩니다.

 

 

 

@Scheduled(fixedRate = 1000L)
public void schedulingTest() throws InterruptedException {
    LocalDateTime now = LocalDateTime.now();
    System.out.println("현재 시각:" + now);
    Thread.sleep(5000);
}

 

 

->  '시작된 시점'부터 계산합니다. 지정한 주기인 1초가 흘렀지만, 쓰레드가 5초동안 멈추기 때문에 5초가 흐른 뒤 다시 실행됩니다.