백엔드/Kotlin + Spring

[Kotlin Spring] 스프링 스케줄러를 이용한 매일 오전 3시 작업 예약하기

커피와 개발자 2024. 11. 16. 03:25
728x90
반응형

서론

이전에 뉴스 기사 스크래핑 및 요약 기능을 구현한 후 자동화를 시키기 위해 스프링 스케줄러를 사용하기로 했다.

목표는 최신 뉴스 기사 스크래핑 및 요약을 매일 사람들이 이용하지 않는 시간대에 업데이트하는 것이다.

 

 

Spring Scheduler

스프링의 스케줄러는 특정 시간에 특정 작업을 자동으로 실행하게 해주는 기능이다.

1. 기본 설정

@Configuration
@EnableScheduling
class JpaConfig

 

 

2. 주요 어노테이션

@Scheduled 어노테이션을 사용하면 된다.

@Component
class ScheduledTasks {

    // 1. 고정 간격으로 실행
    @Scheduled(fixedRate = 5000) // 5초마다
    fun reportCurrentTime() {
        // 작업 내용
    }

    // 2. 이전 작업 완료 후 일정 시간 후 실행
    @Scheduled(fixedDelay = 5000) // 이전 작업 완료 후 5초 후
    fun processQueues() {
        // 작업 내용
    }

    // 3. Cron 표현식 사용
    @Scheduled(cron = "0 0 9 * * ?") // 매일 오전 9시
    fun dailyReport() {
        // 작업 내용
    }
}

 

3. Cron 표현식

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ 요일 (0-7) (0,7 = 일요일)
│    │    │    │    └──── 월 (1-12)
│    │    │    └───────── 일 (1-31)
│    │    └────────────── 시 (0-23)
│    └─────────────────── 분 (0-59)
└──────────────────────── 초 (0-59)
// 매일 자정
@Scheduled(cron = "0 0 0 * * ?")

// 평일 오전 9시
@Scheduled(cron = "0 0 9 * * MON-FRI")

// 매시 30분
@Scheduled(cron = "0 30 * * * ?")

 

사용 예시


@Component
class NewsArticleScrapingScheduler(
    private val newsArticleScrapingService: NewsArticleScrapingService,
    private val newsArticleService: NewsArticleService,
    private val aiService: OpenAiService,
) {
    private val log = LoggerFactory.getLogger(javaClass)

    @Scheduled(cron = "0 0 3 * * *") // 매일 오전 3시에 작업 수행
    @Transactional
    fun scrapNewsArticlesDaily() {
        try {
            log.info("Starting daily news scraping...")
            val newsArticleList = mutableListOf<NewsArticle>()

            // 뉴스 스크래핑 수행
            newsArticleList.addAll(newsArticleScrapingService.scrapEconomyNews())
            newsArticleList.addAll(newsArticleScrapingService.scrapESGEconomy())

            // AI 요약 생성
            log.info("Generating AI summaries for ${newsArticleList.size} articles...")
            newsArticleList.map { it.aiSummary = aiService.aiSummary(it.content) }

            // DB 저장
            val savedCount = newsArticleService.saveNewsArticles(newsArticleList)
            log.info("Successfully scraped and saved $savedCount news articles")
        } catch (e: Exception) {
            log.error("Failed to scrap news articles: ${e.message}", e)
        }
    }
}

 

장점과 활용

  1. 자동화
    • 정기적인 데이터 백업
    • 캐시 갱신
    • 리포트 생성
    • 알림 발송
  2. 모니터링
    • 시스템 상태 체크
    • 리소스 사용량 모니터링
    • 에러 로그 분석
  3. 데이터 처리
    • 배치 작업 실행
    • 데이터 정리/최적화
    • 임시 데이터 삭제
728x90
반응형