初始化器

初始化器在程序启动后执行,在初始化器的默认实现中会做两件事

  1. 装载时间轮,通过任务加载器全量同步启动状态的任务到时间轮

  2. 启动定时器

public class DefaultScheduleTaskInitializer implements ScheduleTaskInitializer, InitializingBean, DisposableBean {

    private final TimeWheel timeWheel;
    private final ScheduleTaskService scheduleTaskService;
    private final TaskJobScheduler taskJobScheduler;

    public DefaultScheduleTaskInitializer(TimeWheel timeWheel,
                                          ScheduleTaskService scheduleTaskService,
                                          TaskJobScheduler taskJobScheduler) {
        this.timeWheel = timeWheel;
        this.scheduleTaskService = scheduleTaskService;
        this.taskJobScheduler = taskJobScheduler;
    }

    @Override
    public void initialize() {
        loadTask();// 1. 装载时间轮
        taskJobScheduler.start();// 2. 启动定时器
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            initialize();
            log.info("Schedule task initialize succeed");
        }catch (Exception e){
            log.error("Schedule task initialize failed, {}", e.getMessage());
        }
    }

    @Override
    public void destroy() throws Exception {
        taskJobScheduler.stop();
    }

    private void loadTask(){
        Collection<ScheduleTask> scheduleTasks = scheduleTaskService.loadTask();
        if (CollectionUtils.isEmpty(scheduleTasks)){
            return;
        }

        for (ScheduleTask task : scheduleTasks) {
            timeWheel.put(task.getTaskId(), task.getCronExpression());
        }
    }
}