package com.huatek.busi.service.impl.job;

import java.util.List;

import javax.annotation.PostConstruct;

import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import com.huatek.busi.entity.ScheduleJob;
import com.huatek.busi.service.job.ScheduleJobService;

/**
  * @ClassName: JobInitService
  * @FullClassPath: com.huatek.busi.job.JobInitService
  * @Description: 初始化定时任务
  * @author: Arno
  * @date: Jul 3, 2019 2:21:56 PM
  * @version: 1.0
  */

@Component
public class JobInitService {

	 protected final Logger logger = LoggerFactory.getLogger(JobInitService.class);
	 
	@Autowired
    private SchedulerFactoryBean schedulerFactoryBean ;
	
	@Autowired
	private ScheduleJobService scheduleJobService; 
	
	
	@PostConstruct
	public void init(){
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		List<ScheduleJob> scheduleJobList = scheduleJobService.findAll();
		//初始化定时器
		for(ScheduleJob scheduleJob : scheduleJobList){
			CronTrigger cronTrigger = ScheduleManager.getCronTrigger(scheduler, scheduleJob.getId());
            //如果不存在，则创建
            if(cronTrigger == null) {
            	ScheduleManager.createScheduleJob(scheduler, scheduleJob);
            }else {
            	ScheduleManager.updateScheduleJob(scheduler, scheduleJob);
            }
		}
	}
}
