현 시스템을 이용하지 않는 외부 기능이 생겨 데이터 처리 작업을 해야 되는 일이 생겼다.
이전에 작업하였던 스프링배치(배치+쿼츠)와 스프링 스케줄 어떤 걸로 구현할 지 고민하다가
데이터 처리할 양이 상당히 적고 (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
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
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
스프링 배치(Spring Batch) 시작하기 !😭
스프링 배치 5가 릴리즈된지 거의 1년이 흘렀는데 이 때는 안보고 있다가.. 😛 급하게 스케줄러와 배치를 이용해야 되는 일이 생겻다 😥 내가 만들어야 할 프로그램 프로세스 흐름은 이와 같다.
djlife.tistory.com
'Develop > Back-End' 카테고리의 다른 글
[Java] 리플렉션(Reflection) 이란 무엇인가요? (6) | 2024.10.07 |
---|---|
[Java] 모던 자바(Modern JAVA) 란 무엇인가!!!!😒 (feat. 새롭게 추가된 기능들) (105) | 2024.03.24 |
스프링 배치(Spring Batch) 시작하기 !😭 (131) | 2024.02.03 |
스프링 부트 카카오 로그인 API 기능 추가하기 😳 (114) | 2023.10.22 |
Spring Boot 환경에서 Appium을 통해 모바일 환경 테스트 하기 + 플러그인 (09.19 수정) (66) | 2023.09.17 |