package com.zehong.quartz.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 定时任务配置
 *
 * @author zehong
 */
@Configuration
public class ScheduleConfig
{
    @Autowired
    private ApplicationContext applicationContext;
    @Bean
    public SpringBeanJobFactory springBeanJobFactory() {
        SpringQuartzJobFactory jobFactory = new SpringQuartzJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource)
    {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setJobFactory(springBeanJobFactory());
        factory.setDataSource(dataSource);

        Properties prop = new Properties();
        prop.put("org.quartz.scheduler.instanceName", "ZhMESDeviceScheduler");
        prop.put("org.quartz.scheduler.instanceId", "AUTO");

        // 线程池配置
        prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
        prop.put("org.quartz.threadPool.threadCount", "15");
        prop.put("org.quartz.threadPool.threadPriority", "5");

        // JobStore配置 - 关键修复：关闭集群模式
        prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
        prop.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
        prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
        prop.put("org.quartz.jobStore.isClustered", "false"); // 单机部署关闭集群
        prop.put("org.quartz.jobStore.useProperties", "false"); // 使用类型安全的方式

        // 其他优化配置
        prop.put("org.quartz.jobStore.misfireThreshold", "60000");
        prop.put("org.quartz.scheduler.skipUpdateCheck", "true");

        factory.setQuartzProperties(prop);
        factory.setSchedulerName("ZhMESDeviceScheduler");
        factory.setStartupDelay(5); // 增加启动延迟
        factory.setApplicationContextSchedulerContextKey("applicationContext");
        factory.setOverwriteExistingJobs(true);
        factory.setAutoStartup(true);
        factory.setWaitForJobsToCompleteOnShutdown(true);

        return factory;
    }

}
