- 스케줄러 설정
@EnableScheduling
@EnableBatchProcessing(dataSourceRef = "batchDataSource", transactionManagerRef = "batchTransactionManager")
@Import({BatchAutoConfiguration.class})
@SpringBootApplication
public class SpringbatchApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbatchApplication.class, args);
}
}
@EnableScheduling를 붙여 Spring Scheduler를 활성화한다.
- BatchController
@RestController
@RequestMapping("/batch")
@RequiredArgsConstructor
public class BatchController {
private final BatchService batchService; // Di
@GetMapping("/run-job")
public String runBatchJob() {
return batchService.runJob();
}
}
@Service
@RequiredArgsConstructor
public class BatchService {
private final JobLauncher jobLauncher; // job을 실행시키는 jobLauncher
private final Job trMigrationJob; // 실행시킬 job
@Scheduled(cron = "59 59 23 * * *", zone = "Asia/Seoul") // 서울 시간을 기준으로 매일 오후 11시 59분 59초에 실행
public String runJob() {
try { // job을 실행시키는 코드
JobExecution jobExecution = jobLauncher.run(trMigrationJob, new JobParametersBuilder()
.addLong("time", System.currentTimeMillis()).toJobParameters());
return "Job Execution Status: " + jobExecution.getStatus();
} catch (Exception e) {
e.printStackTrace();
return "Job Execution failed: " + e.getMessage();
}
}
}
@Scheduled로 스케줄러를 사용하고 zone으로 지역을 설정하고 cron 표현식으로 실행 시간을 지정해준다.
zone을 설정하지 않으면 기본적으로 local time zone이 설정된다.
cron 표현식으로 작업 시간을 예약할 수 있다.
@Scheduled(cron = "* * * * * *")
첫 번째 *부터
초(0-59)
분(0-59)
시간(0-23)
일(1-31)
월(1-12)
요일(0-6) (0: 일, 1: 월, 2:화, 3:수, 4:목, 5:금, 6:토)
'Back-end' 카테고리의 다른 글
[Spring Security] #1 기본 구조 (1) | 2024.06.15 |
---|---|
[Spring Batch] DB에서 데이터 읽고 DB에 쓰기 (0) | 2024.06.09 |
[Spring Batch] Spring Batch 구조 및 테스트 (0) | 2024.06.08 |
[JPA] JPA에서 On Delete Cascade 제약조건 사용하기 (1) | 2024.06.03 |
[UnitTest] JUnit과 Mockito 기반 Spring 단위테스트 (2) | 2024.05.31 |