예전에 Quartz를 이용해서 작업할 때 보다는 @Scheduled annotation을 사용하면 배치 작업을 무척 쉽게 만들 수 있습니다.
얼마나 간단하고 쉬운지 한번 만들어 보겠습니다.
먼저 프로젝트를 하나 생성 합니다.
프로젝트 이름을 대충 적어주고
화면을 만들건 아니지만 일단 Web을 추가해서 생성 합니다.
이제 설정을 해줍니다.
Application 메인 파일을 열고
|
package com.copycoding.batch;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication @EnableScheduling public class BatchApplication {
public static void main(String[] args) { SpringApplication.run(BatchApplication.class, args); } } |
@EnableScheduling 어노테이션을 추가해 줍니다.
그리고 실제 스케쥴 작업할 class 파일을 만듭니다.
|
package com.copycoding.batch;
import java.time.LocalDateTime;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component;
@Component public class ScheduleTask {
@Scheduled(fixedDelay = 2000) public void task1() { System.out.println("The current date (1) : " + LocalDateTime.now()); }
@Scheduled(fixedDelayString = "${spring.task.fixedDelay}") public void task2() { System.out.println("The current date (2) : " + LocalDateTime.now()); }} |
중요한건 class 파일에 @Component를 설정해야 합니다. 이렇게 두개의 어노테이션을 적어주기만 하면 설정은 끝입니다.
이제 메소드를 만들고 @Scheduled를 이용해서 메소드의 작동 시간을 입력하고 코딩을 해줍니다. 위에 있는 프로그램을 실행하면
이런식으로 결과를 얻을 수 있습니다. annotation만으로 쉽게 배치 작업이 완료 됩니다.
@Scheduled() 어노테이션에 들어가는 설정들을 정리해 보았습니다.
|
fixedDelay |
@Scheduled(fixedDelay = 1000) 이전 작업이 종료된 후 설정시간(밀리터리세컨드) 이후에 다시 시작 |
|
fixedDelayString |
@Scheduled(fixedDelay = “1000”) fixedDelay와 동일 하고 지연시간(the delay in milliseconds)을 문자로 입력 |
|
fixedRate |
@Scheduled(fixedRate = 1000) 설정된 시간마다 시작을 한다. 즉 이전 작업이 종료되지 않아도 시작. |
|
fixedRateString |
@Scheduled(fixedRateString = “1000”) fixedRate와 동일 하고 지연시간(the delay in milliseconds)을 문자로 입력 |
|
initialDelay |
@Scheduled(fixedRate = 5000, initialDelay = 3000) 프로그램이 시작하자마자 작업하는게 아닌 시작을 설정된 시간만큼 지연하여 작동을 시작 한다.(예제는 3초 후 부터 5초 간격으로 작업) |
|
initialDelayString |
@Scheduled(fixedRate = 5000, initialDelay = “3000”) initialDelay와 동일 하고 지연시간(the delay in milliseconds)을 문자로 입력 |
|
cron |
@Scheduled(cron = "* * * * * *") 첫번째 부터 위치별 설정 값은 초(0-59) 분(0-59) 시간(0-23) 일(1-31) 월(1-12) 요일(0-7) |
|
zone |
@Scheduled(cron = "0 0 14 * * *" , zone = "Asia/Seoul") 미설정시 local 시간대를 사용한다. oracle에서 제공하는 문서를 참조하여 입력 한다. https://docs.oracle.com/cd/B13866_04/webconf.904/b10877/timezone.htm |
- copy coding -
'Java' 카테고리의 다른 글
| [Firebase] Spring Boot에서 Firestore 데이베이스 CRUD 테스트 (0) | 2020.06.13 |
|---|---|
| [ObjectMapper] VO를 JSON 형태의 String으로 변환 (0) | 2020.05.10 |
| [OAuth2] Unsupported grant type: password (0) | 2020.04.17 |
| Maven jQuery Validation 이용 form input 유효성 검사 (0) | 2020.03.29 |
| JAVA substring split 특수문자 문자열 자르기 (0) | 2020.03.15 |