package com.foreverwin.mesnac.quartz.configuration;

import org.quartz.JobListener;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author Ervin Chen
 * @date 2020/10/22 18:19
 */
@Component
@ConditionalOnProperty(prefix = "quartz", name="enabled", havingValue = "true")
public class JobListenerConfiguration {

    private AutowireCapableBeanFactory factory;

    public JobListenerConfiguration(AutowireCapableBeanFactory factory) {
        this.factory = factory;
    }

    @Autowired
    private Scheduler scheduler;

    @PostConstruct
    public void init(){
        try {
            JobListener listener = new SystemJobListener();
            factory.autowireBean(listener);
            scheduler.getListenerManager().addJobListener(listener);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
