Runjob(런잡 프로젝트)/SpringBoot + Kotlin

[SpringBoot + Kotlin] @scheduled로 스케줄 처리 및 corn 설정

맏리믓 2023. 4. 24. 17:02

들어가며

- 앞서 했었던 영화 정보나 상영중인 영화 리스트 같은 경우는하루에 한번씩 최신화 해 주어야 하는 기능이다.

- 이처럼 프로그램을 짜다 보면 따로 실행 명령을 하지 않아도 주기적으로 자동으로 실행 해 주었으면 하는 기능 들이 있다.

- 이러한 문제를 해결 할 수 있는 방법이 바로 스케쥴러를 사용하는 것이다.


@Scheduled 사용법

1. Scheduled 

- 스케쥴링을 사용하고자 하는 클래스 위에 @EnableScheduling 을 추가한다.

- 주기적으로 실행하고자 하는 메소드 위에 @Scheduled(cron = "~~") 을 붙히면 된다.

 

2. cron

출처 ) https://itworldyo.tistory.com/40

- 이때 각 자리에

 [*] : 모든 조건

 [?] : 날짜와 요일에서 설정값이 없을때 

 [-] :  범위를 지정 할 때

 [,] : 여러 값을 한번에 지정할 때

 [/] : 초기 값과 증가치를 설정 할 때

 [L] : 날짜와 요일 부분에서 지정할 수 있는 마지막 값으로 설정 할 때

 [W] : 일(4) 부분에서 가장 가까운 평일로 설정 할 때

 [#] : 요일에서 원하는 주차(ex 3#2 == 수요일 2번째 주)

 

- 예제 (매월 10일 오전 11시)

  - (cron = "0 1 1 10 * *")

- 예제 (10분마다 실행)

  - (cron = "0 0/10 * * * *")


실제로 스케줄러 구현

- 모든 class 에서 scheduler 를 사용 할 수 있도록 "Application.kt" 에 "EnableScheduling" 을 추가해 주었다.

- 그 후 현재 시간과 Hello World 를 같이 찍어 주는 메소드 하나를 생성하여 scheduled 설정을 해 주었다.

- 두번째 코드의 가장 아래 메소드가 바로 그것이다.

//Application.kt

package com.example.runjob_blog

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.scheduling.annotation.EnableScheduling

@SpringBootApplication
@EnableScheduling
class RunjobBlogApplication

fun main(args: Array<String>) {
   runApplication<RunjobBlogApplication>(*args)
}
//controller.kt

package com.example.runjob_blog.Controller

import com.example.runjob_blog.Service.movieInfoService
import com.example.runjob_blog.Service.testService
import com.example.runjob_blog.Utils.request_API
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.time.LocalDateTime

@RestController
@RequestMapping("/test")
class BlogTestController(
    val testService: testService,
    val movieInfoService: movieInfoService
) {
    @GetMapping("/DBsave")
    fun DBsave(){
        testService.saveTest()
    }

    @GetMapping("/get")
    fun GET_API(): String{
        val result = request_API.useGETApi("https://movie.daum.net/api/premovie?page=1&size=100")
        return result
    }

    @GetMapping("/post")
    fun POST_API(): String{
        val result = request_API.runPOSTApi()
        return result
    }

    @GetMapping("crawling")
    fun Crawling() {
        movieInfoService.saveTimeTable("161806")
    }

    @Scheduled(cron = "0/10 * * * * *")
    fun Schedule_test(){
        println("Hello World - " + LocalDateTime.now())
    }
}

결과

- 10초마다 아주 잘 찍는것을 볼 수 있다.