Cron을 사용하여 일정한 시간 간격으로 반복적인 작업을 수행.
사용 방법 : @Scheduled(cron = "* * * * * *")
첫번째 부터 초(0-59) 분(0-59) 시간(0-23) 일(1-31) 월(1-12) 요일(0-7)
// 초, 분, 시, 일, 월, 주 순서
@Scheduled(cron = "0 0 1 * * *") // 매일 새벽 1시
public void updatePrice() throws InterruptedException {
log.info("가격 업데이트 실행");
List<Product> productList = productRepository.findAll();
for (Product product : productList) {
// 1초에 한 상품 씩 조회합니다 (NAVER 제한)
TimeUnit.SECONDS.sleep(1);
// i 번째 관심 상품의 제목으로 검색을 실행합니다.
String title = product.getTitle();
List<ItemDto> itemDtoList = naverApiService.searchItems(title);
if (itemDtoList.size() > 0) {
ItemDto itemDto = itemDtoList.get(0);
// i 번째 관심 상품 정보를 업데이트합니다.
Long id = product.getId();
try {
productService.updateBySearch(id, itemDto);
} catch (Exception e) {
log.error(id + " : " + e.getMessage());
}
}
}
}