package cn.datax.service.quartz.config;

import cn.datax.service.quartz.quartz.utils.ScheduleUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import lombok.AllArgsConstructor;
import org.quartz.Scheduler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;

@Configuration
@AllArgsConstructor
public class SchedulerConfig {

    private final DataSource dataSource;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        // 手动从多数据源中获取 quartz数据源
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        DataSource quartz = ds.getDataSource("quartz");
        factory.setDataSource(quartz);
        return factory;
    }

    @Bean(name = "scheduler")
    public Scheduler scheduler() {
        Scheduler scheduler = schedulerFactoryBean().getScheduler();
        // 设置ScheduleUtil的定时处理对象
        ScheduleUtil.setScheduler(scheduler);
        return scheduler;
    }
}
