본문 바로가기

Develop/Back-End

[SpringBoot] 스프링을 이용하여 가벼운(간단한) 스케줄링 작업 처리하는 방법 😁

 

현 시스템을 이용하지 않는 외부 기능이 생겨 데이터 처리 작업을 해야 되는 일이 생겼다.

 

이전에 작업하였던 스프링배치(배치+쿼츠)와 스프링 스케줄 어떤 걸로 구현할 지 고민하다가

데이터 처리할 양이 상당히 적고 (100 Row 미만) 작업이 복잡하지 않아 스케줄러를 이용하기로 결정 😒

 

* 스케줄러 : 특정한 시간에 등록한 작업을 자동으로 실행 시키는 것을 의미합니다.

Spring에서 제공하는 스케줄러로는 Spring Scheduler(종속 추가 x), Spring Quartz(종속 추가 필요)가 있습니다.


스프링 스케줄러 사용 방법

1. 스케줄링을 활성화 하려면 @EnableScheduling 주석을 메인 Spring Boot 애플리케이션 클래스에 추가하거나 프로젝트에서 만든 구성 클래스에 추가하기만 하면 된다. 👍

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

@SpringBootApplication
@EnableScheduling
public class ApiApplication {

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

}

 

 

2. 스케줄이 활성화 되었다면 @Scheduled  어노테이션을 이용하여 스케줄링 작업할 코드를 작성하면 끝 엄청 간단하다

해당 어노테이션에서는 세가지 설정이 가능하다. 나는  cron표현식을 이용했는데 보다 자세한 이용 방법은 아래 참조 링크 확인하길! 😂

 

fixedDelay : scheduler가 끝나는 시간 기준으로 설정한 밀리초 간격으로 실행 

fixedRate : scheduler가 시작하는 기준으로 설정한 밀리초 간격으로 실행 

cron 표현식 : cron = 0? : 앞에서 부터 초, 분, 시, 일, 월, 요일(연도)순으로 진행

 

import com.elysian.api.domain.temp.service.TempService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
@Slf4j
@RequiredArgsConstructor
public class TempTask {

    private final TempService tempService;

    @Value("${schedule.use}")
    private boolean useSchedule;

    @Scheduled(cron = "${schedule.cron}")
    public void mainJob() {
        try {
            if (useSchedule) {
                String formatDate = LocalDateTime.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
                log.info("Batch Start Date = {}",formatDate);
                tempService.sync(formatDate);
            }
        }  catch (Exception e) {
            log.info("* Batch 시스템이 예기치 않게 종료되었습니다. Message: {}", e.getMessage());
        }
    }
}

 


참고 Ref.

 

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

 

Getting Started | Scheduling Tasks

Although scheduled tasks can be embedded in web applications, the simpler approach (shown in this guide) creates a standalone application. To do so, package everything in a single, executable JAR file, driven by a Java main() method. The following snippet

spring.io

 

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableScheduling.html

 

EnableScheduling (Spring Framework 6.1.11 API)

Enables Spring's scheduled task execution capability, similar to functionality found in Spring's XML namespace. To be used on @Configuration classes as follows: @Configuration @EnableScheduling public class AppConfig { // various @Bean definitions } This e

docs.spring.io

 

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html

 

Scheduled (Spring Framework 6.1.11 API)

A cron-like expression, extending the usual UN*X definition to include triggers on the second, minute, hour, day of month, month, and day of week.

docs.spring.io

 

https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm

 

Cron Expressions

A Cron Expressions Cron expressions are used to configure instances of CronTrigger, a subclass of org.quartz.Trigger. A cron expression is a string consisting of six or seven subexpressions (fields) that describe individual details of the schedule. These f

docs.oracle.com

 

https://djlife.tistory.com/31

 

스프링 배치(Spring Batch) 시작하기 !😭

스프링 배치 5가 릴리즈된지 거의 1년이 흘렀는데 이 때는 안보고 있다가.. 😛 급하게 스케줄러와 배치를 이용해야 되는 일이 생겻다 😥 내가 만들어야 할 프로그램 프로세스 흐름은 이와 같다.

djlife.tistory.com

 

반응형