SpringBoot集成Quartz

1.Job属性注入

public class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory
        implements ApplicationContextAware {

    private AutowireCapableBeanFactory beanFactory;

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        beanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {

        final Object job = super.createJobInstance(bundle);
        //自动装配类相关属性
        beanFactory.autowireBean(job);
        return job;
    }
}

2.Job工具类

public class SchedulerUtil {

    //定时任务Scheduler的工厂类,Quartz提供
    private static StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
    //CronTrigger的工厂类
    private static CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
    //JobDetail的工厂类
    private static JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
    //自动注入Spring Bean的工厂类
    private static AutoWiringSpringBeanJobFactory jobFactory =
            new AutoWiringSpringBeanJobFactory();
    //定时任务Scheduler的工厂类,Spring Framework提供
    private static SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();

    static {
        //加载指定路径的配置
        schedulerFactoryBean.setConfigLocation(new ClassPathResource("quartz.properties"));
    }

    /**
     * 创建定时任务,根据参数,创建对应的定时任务,并使之生效
     * @param config
     * @param context
     * @return
     */
    public static boolean createScheduler(SysJobConfig config,
                                          ApplicationContext context) {
        try {
            //创建新的定时任务
            return create(config, context);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除旧的定时任务,创建新的定时任务
     * @param oldConfig
     * @param config
     * @param context
     * @return
     */
    public static Boolean modifyScheduler(SysJobConfig oldConfig,SysJobConfig config,
                                          ApplicationContext context) {
        if (oldConfig == null || config == null || context == null) {
            return false;
        }
        try {
            String oldJobClassStr = oldConfig.getFullEntity();
            String oldName = oldJobClassStr + oldConfig.getId();
            String oldGroupName = oldConfig.getGroupName();
            //1、清除旧的定时任务
            delete(oldName, oldGroupName);
            //2、创建新的定时任务
            return create(config, context);
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 提取的删除任务的方法
     * @param oldName
     * @param oldGroupName
     * @return
     * @throws SchedulerException
     */
    public static Boolean delete(String oldName, String oldGroupName)
            throws SchedulerException {
        TriggerKey key = new TriggerKey(oldName, oldGroupName);
        Scheduler oldScheduler = schedulerFactory.getScheduler();
        //根据TriggerKey获取trigger是否存在,如果存在则根据key进行删除操作
        Trigger keyTrigger = oldScheduler.getTrigger(key);
        if (keyTrigger != null) {
            oldScheduler.unscheduleJob(key);
        }
        return true;
    }

    /**
     * 提取出的创建定时任务的方法
     * @param config
     * @param context
     * @return
     */
    public static Boolean create(SysJobConfig config, ApplicationContext context) {
        try {
            //创建新的定时任务
            String jobClassStr = config.getFullEntity();
            Class clazz = Class.forName(jobClassStr);
            String name = jobClassStr + config.getId();
            String groupName = config.getGroupName();
            String description = config.toString();
            String time = config.getCronTime();

            JobDetail jobDetail = createJobDetail(clazz, name, groupName, description);
            if (jobDetail == null) {
                return false;
            }
            Trigger trigger = createCronTrigger(jobDetail,
                    time, name, groupName, description);
            if (trigger == null) {
                return false;
            }

            jobFactory.setApplicationContext(context);

            schedulerFactoryBean.setJobFactory(jobFactory);
            schedulerFactoryBean.setJobDetails(jobDetail);
            schedulerFactoryBean.setTriggers(trigger);
            schedulerFactoryBean.afterPropertiesSet();
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
            return true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 根据指定的参数,创建JobDetail
     * @param clazz
     * @param name
     * @param groupName
     * @param description
     * @return
     */
    public static JobDetail createJobDetail(Class clazz, String name,
                                            String groupName, String description) {
        jobDetailFactory.setJobClass(clazz);
        jobDetailFactory.setName(name);
        jobDetailFactory.setGroup(groupName);
        jobDetailFactory.setDescription(description);
        jobDetailFactory.setDurability(true);
        jobDetailFactory.afterPropertiesSet();
        return jobDetailFactory.getObject();
    }

    /**
     * 根据参数,创建对应的CronTrigger对象
     *
     * @param job
     * @param time
     * @param name
     * @param groupName
     * @param description
     * @return
     */
    public static CronTrigger createCronTrigger(JobDetail job, String time,
                                                String name, String groupName, String description) {
        factoryBean.setName(name);
        factoryBean.setJobDetail(job);
        factoryBean.setCronExpression(time);
        factoryBean.setDescription(description);
        factoryBean.setGroup(groupName);
        try {
            factoryBean.afterPropertiesSet();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return factoryBean.getObject();
    }
}

3.Quartz配置

#默认或是自己改名字都行
org.quartz.scheduler.instanceName: DefaultQuartzScheduler

#如果使用集群,instanceId必须唯一,设置成AUTO
org.quartz.scheduler.instanceId = AUTO

//通过RMI导出
org.quartz.scheduler.rmi.export: false
//连接到远端提供服务的scheduler
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false

//自带的线程池
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
//并行执行job可用的线程数
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
//下一次触发时间
org.quartz.jobStore.misfireThreshold: 60000

4.启动时读取数据库中的执行时间

@Configuration
public class autoconfig {

    @Autowired
    SysJobConfigRepository repository;

    @Autowired
    ApplicationContext context;

    @Bean
    public StdSchedulerFactory schedulerFactory(){
        StdSchedulerFactory factory = new StdSchedulerFactory();
        SysJobConfig jobConfig = repository.getById("1");
        boolean scheduler = jobUtils.createScheduler(jobConfig, context);
        System.out.println(scheduler == true? "执行成功":"执行失败");
        return factory;
    }
}

 

你可能感兴趣的:(学习日记)