package com.heyu.api.schedule;

import com.heyu.api.data.entity.calca.ScheduleJobEntity;
import com.heyu.api.data.service.calca.ScheduleJobService;

import lombok.extern.slf4j.Slf4j;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;


@Component
@Slf4j
public class ScheduleConfigBean {

    @Autowired
    private Scheduler scheduler;


    @Autowired
    private ScheduleJobService scheduleJobService;

    /**
     * 项目启动时，初始化定时器
     */
    @PostConstruct
    public void init() {
        List<ScheduleJobEntity> scheduleJobEntityList = scheduleJobService.selectScheduleJobsByStatus(0);
        for(ScheduleJobEntity scheduleJob : scheduleJobEntityList) {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            log.info("初始化 job " + scheduleJob.getBeanName() + "." + scheduleJob.getMethodName());
            //如果不存在，则创建
            if (cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }

    }
}
