Scheduler
1. 사용하는 이융
- 주기적으로 업데이트 해야하는 상황일 때 사용한다.
2. 사용 예시
@Slf4j(topic = "Scheduler")
@Component
@RequiredArgsConstructor
public class Scheduler {
private final NaverApiService naverApiService;
private final ProductService productService;
private final ProductRepository productRepository;
@Scheduled(cron = "0 0 1 * * *")
public void updatePrice() throws InterruptedException {
log.info("가격 업데이트 실행");
List<Product> productList = productRepository.findAll();
for (Product product : productList) {
TimeUnit.SECONDS.sleep(1);
String title = product.getTitle();
List<ItemDto> itemDtoList = naverApiService.searchItems(title);
if (itemDtoList.size() > 0) {
ItemDto itemDto = itemDtoList.get(0);
Long id = product.getId();
try {
productService.updateBySearch(id, itemDto);
} catch (Exception e) {
log.error(id + " : " + e.getMessage());
}
}
}
}
}
cron: 운영체제에서 특정 시간 마다 자동으로 수행되게 하는 명령어
cron Expression에 따라 특정한 시간에 특정한 작업을 하게한다.
- "초 분 시 일 월 요일"
참고
Cron Expression