스케줄을 설정하는데 모든 스케줄에 공통 로직이 들어가는 경우가 있을 수 있습니다.
그러면 모든 @Scheduled 를 찾아서 공통 로직을 넣어줄 수도 있죠.
아래 코드처럼요.
@Slf4j
@EnableScheduling
@RequiredArgsConstructor
@Component
public class Scheduler {
private final ScheduleService scheduleService;
private final CommonCodeService commonCodeService;
@Scheduled(cron = "0 0 2 * * *")
public void schedulingGameInformation() {
if (commonCodeService.something()) {
log.info("Start Game Information Scheduler!");
scheduleService.schedulingGameInformation(LocalDateTime.now());
}
}
@Scheduled(cron = "0 0 3 * * *")
public void schedulingGameGroup() {
if (commonCodeService.something()) {
log.info("Start Game Group Scheduler!");
scheduleService.schedulingGameGroup(LocalDateTime.now());
}
}
@Scheduled(cron = "0 0 4 * * *")
public void schedulingPlayerProfile() {
if (commonCodeService.something()) {
log.info("Start Player Profile Scheduler!");
scheduleService.schedulingPlayerProfile(LocalDateTime.now());
}
}
@Scheduled(cron = "0 0/2 6-20 * * *")
public void schedulingLiveScore() {
if (commonCodeService.something()) {
log.info("Start Live Score Scheduler!");
scheduleService.schedulingLiveScore(LocalDateTime.now());
}
****}
}
그런데 만약 @Scheduled 가 100개라면 어떨까요?
복사 붙여넣기를 100번 해야되는데 시간도 오래걸릴 뿐더러 실수할 확률도 생기겠죠?
이런 경우에 SchedulingConfigurer 인터페이스를 implements 해서 configureTasks 메서드를 구현한다면 좀 더 간단하게 처리할 수 있습니다.
바로 코드로 확인해봅시다.
@EnableScheduling
@RequiredArgsConstructor
@Configuration
public class SchedulingConfiguration implements SchedulingConfigurer {
private final CommonCodeService commonCodeService;
private final Scheduler scheduler;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
if (commonCodeService.something()) {
taskRegistrar.addCronTask(scheduler::schedulingGameInformation, "0 0 2 * * *");
taskRegistrar.addCronTask(scheduler::schedulingGameGroup, "0 0 3 * * *");
taskRegistrar.addCronTask(scheduler::schedulingPlayerProfile, "0 0 4 * * *");
taskRegistrar.addCronTask(scheduler::schedulingLiveScore, "0 0/2 6-20 * * *");
}
}
}
configureTasks 메서드는 인자로 ScheduledTaskRegistrar 클래스를 받습니다.
그리고 ScheduledTaskRegistrar 클래스에 구현된 addCronTask 메서드를 사용해서 간편하게 스케줄을 등록할 수 있죠.