[SPRING] Scheduler 구현

야부엉·2023년 11월 22일

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 * * *") // 매일 새벽 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());
                }
            }
        }
    }

}
  • cron: 운영체제에서 특정 시간 마다 자동으로 수행되게 하는 명령어
  • cron Expression에 따라 특정한 시간에 특정한 작업을 하게한다.
  • "초 분 시 일 월 요일"

참고

Cron Expression

profile
밤낮없는개발자

0개의 댓글