Spring Boot集成Quartz注入Spring管理的類

摘要: 在Spring Boot中使用Quartz時,在JOB中通常須要引用Spring管理的Bean,經過定義Job Factory實現自動注入java

Spring有本身的Schedule定時任務,在Spring boot中使用的時候,不能動態管理JOB,因而就使用Quartz來實現。spring

在Spring Boot中配置Quartz:ide

import java.io.IOException;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
@EnableScheduling
public class QuartzSchedule {

    @Autowired
    private MyJobFactory myJobFactory;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();

        factory.setOverwriteExistingJobs(true);

        // 延時啓動
        factory.setStartupDelay(20);

        // 加載quartz數據源配置
        factory.setQuartzProperties(quartzProperties());

        // 自定義Job Factory,用於Spring注入
        factory.setJobFactory(myJobFactory);

        return factory;
    }

    /**
     * 加載quartz數據源配置
     * 
     * @return
     * @throws IOException
     */
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

}

 

爲了在JOB中使用Spring管理的Bean,須要從新定義一個Job Factory:ui

@Component
public class MyJobFactory extends AdaptableJobFactory {
    
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 調用父類的方法
        Object jobInstance = super.createJobInstance(bundle);
        // 進行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

 

而後在JOB中就能夠使用Spring管理的Bean了this

public class MyJob implements Job, Serializable {
    private static final long serialVersionUID = 1L;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SomeService someService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        someService.doSomething();
    }
}

 

下面代碼是建立JOB:spa

JobDetail jobDetail = JobBuilder.newJob(((Job) Class.forName(job.getClazz()).newInstance()).getClass())
                    .withIdentity(job.getJobName(), job.getJobGroup()).build();
            jobDetail.getJobDataMap().put("extdata", job.getExtData());

            // 表達式調度構建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();
            // 構建一個trigger
            TriggerBuilder<CronTrigger> triggerBuilder = TriggerBuilder.newTrigger().withIdentity(triggerKey)
                    .withSchedule(scheduleBuilder);
            if (job.getStartTime() != null) {
                triggerBuilder.startAt(job.getStartTime());
            }
            if (job.getEndTime() != null) {
                triggerBuilder.endAt(job.getEndTime());
            }
            CronTrigger trigger = triggerBuilder.build();

            scheduler.scheduleJob(jobDetail, trigger);// 注入到管理類

 

 https://my.oschina.net/hhaijun/blog/698498.net

相關文章
相關標籤/搜索