SpringBoot + Quartz 集成

 

Quartz

应用启动加载集群配置

  • @Bean 注解交由 Spring BeanFactory 容器管理

    @Bean
    public JobDetailFactoryBean testJobDetailFactory() {
        JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
        jobDetailFactory.setName("test-job");
        jobDetailFactory.setGroup("sns");
        jobDetailFactory.setJobClass(TestJob.class);
        jobDetailFactory.setDurability(true);
        return jobDetailFactory;
    }
    
    @Bean
    public CronTriggerFactoryBean testJobTrigger(
        @Qualifier("testJobDetailFactory") JobDetailFactoryBean factory) {
        CronTriggerFactoryBean tigger = new CronTriggerFactoryBean();
        if (factory.getObject() != null) {
            tigger.setJobDetail(factory.getObject());
        }
        tigger.setCronExpression("0/10 * * * * ?");
        tigger.setName("test-job-trigger");
        return tigger;
    }

     

    /**
     * SchedulerFactoryBean 实现 InitializingBean,
     * description: quartz定时任务配置
     */
    @Configuration
    public class QuartzConfig {
        private static final Logger LOGGER = LoggerFactory.getLogger(QuartzConfig.class);
        private static final String RESOURCE_NAME = "quartz.properties";
    
        @Resource
        private DataSource dataSource;
        @Autowired
        private SpringJobFactory springJobFactory;
    
        @Bean
        public SchedulerFactoryBean schedulerFactory(Trigger... triggers) {
            SchedulerFactoryBean factory = new SchedulerFactoryBean();
            Properties p = new Properties();
            try {
                p.load(this.getClass().getClassLoader().getResourceAsStream(RESOURCE_NAME));
            } catch (IOException e) {
                LOGGER.error("quartz定时任务加载{}过程中发生错误。");
                throw new Error(e);
            }
            factory.setQuartzProperties(p);
            factory.setDataSource(dataSource);
            factory.setOverwriteExistingJobs(true);
            factory.setStartupDelay(20);
            factory.setTriggers(triggers);
            factory.setJobFactory(springJobFactory);
            return factory;
        }
    }

     

  • 实现 org.springframework.boot.CommandLineRunner ,应用启动成功后开启创建任务

    @Component
    public class InitScheduleOfAppStarted implements CommandLineRunner {
        private static final Logger LOGGER = LoggerFactory.getLogger(InitScheduleOfAppStarted.class);
    
        @Autowired
        private SysJobService sysJobService;
        // 任务 Bean 交由 Spring 管理,并注入任务所需的 Bean 实例
        @Autowired
        private SpringJobFactory springJobFactory;
    
        @Override
        public void run(String... args) throws Exception {
            Map<String, String> runJob = new HashMap();
            runJob.put("jobStatus", "1");
            List<SysJob> jobList = sysJobService.querySysJobList(runJob);
    
            if (null == jobList || jobList.size() <= 0) {
                LOGGER.info("app started,暂无需要执行的任务");
            }
    
            SchedulerFactory sf = new StdSchedulerFactory();
            Scheduler scheduler = sf.getScheduler();
            // 注入 spring 示例,否则执行时找不到 spring 容器中的 bean
            scheduler.setJobFactory(springJobFactory);
            scheduler.start();
    
            for (SysJob sysJob : jobList) {
    
                // jobDetail
                String jobName = sysJob.getJobName();
                String jobGroup = sysJob.getJobGroup();
                JobDetail jobDetail = JobBuilder.newJob(getClass(sysJob.getJobClassPath()).getClass())
                        .withIdentity(jobName, jobGroup)
                        .build();
                // jobTriller
                CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                        .withIdentity(jobName, jobGroup)
                        .withSchedule(CronScheduleBuilder.cronSchedule(sysJob.getJobCron()))
                        .build();
                // 关联
                scheduler.scheduleJob(jobDetail, cronTrigger);
            }
        }
    
        private static Job getClass(String jobClassPath) throws Exception{
            Class<?> aClass = Class.forName(jobClassPath);
            return (Job) aClass.newInstance();
        }
    }

     

  • 继承 org.springframework.scheduling.quartz.AdaptableJobFactory 实例化和依赖注入 Spring Bean 实例

    @Component
    public class SpringJobFactory extends AdaptableJobFactory {
    
        @Autowired
        private AutowireCapableBeanFactory capableBeanFactory;
    
        @Override
        protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
            Object jobInstance = super.createJobInstance(bundle);
            capableBeanFactory.autowireBean(jobInstance);
            return jobInstance;
        }
    }

     

     

posted @ 2020-01-13 15:58  演说家  阅读(221)  评论(0编辑  收藏  举报