由于项目使用spring-boot框架,其框架是为了实现零配置文件去做开发的理念,所以在项目中集成Quartz任务调度并不像spring那样直接配置XML.
首先项目需要用到的jar包:
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>4.1.6.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.quartz-scheduler</groupId>
- <artifactId>quartz</artifactId>
- <version>2.2.1</version>
- </dependency>
交给spring管理的bean,代码如下
- package com.xxx;
- import java.io.IOException;
- import org.mybatis.spring.annotation.MapperScan;
- import org.quartz.JobDetail;
- import org.quartz.Trigger;
- import org.quartz.spi.JobFactory;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.ComponentScan.Filter;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.annotation.FilterType;
- import org.springframework.scheduling.annotation.EnableScheduling;
- import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
- import org.springframework.scheduling.quartz.JobDetailFactoryBean;
- import org.springframework.scheduling.quartz.SchedulerFactoryBean;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.web.WebAppConfiguration;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
- import com.xxx.base.BaseWebAppConfig;
- import com.xxx.cars.quartz.AutowiringSpringBeanJobFactory;
- import com.xxx.cars.quartz.SampleJob;
- @Configuration
- @EnableScheduling
- @ContextConfiguration
- @WebAppConfiguration
- @ComponentScan(basePackages = { "com.xxx" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
- @MapperScan("com.xxx.cars.persistence")
- @EnableTransactionManagement
- @EnableAutoConfiguration
- public class WebAppConfig extends BaseWebAppConfig {
- /**
- * 配置拦截器
- *
- * @author jodie
- * @param registry
- */
- // public void addInterceptors(InterceptorRegistry registry) {
- // registry.addInterceptor(new UserSecurityInterceptor()).addPathPatterns(
- // "/**");
- // }
- @Bean
- public JobFactory jobFactory(ApplicationContext applicationContext) {
- AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
- jobFactory.setApplicationContext(applicationContext);
- return jobFactory;
- }
- /**调度工厂bean
- * @param jobFactory
- * @param sampleJobTrigger
- * @return
- * @author LDX
- * @throws IOException
- */
- @Bean
- public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory,
- @Qualifier("cronJobTrigger") Trigger cronJobTrigger) throws IOException {
- SchedulerFactoryBean factory = new SchedulerFactoryBean();
- // this allows to update triggers in DB when updating settings in config file:
- //用于quartz集群,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
- factory.setOverwriteExistingJobs(true);
- //用于quartz集群,加载quartz数据源
- // factory.setDataSource(dataSource);
- factory.setJobFactory(jobFactory);
- //QuartzScheduler 延时启动,应用启动完20秒后 QuartzScheduler 再启动
- factory.setStartupDelay(20);
- //用于quartz集群,加载quartz数据源配置
- // factory.setQuartzProperties(quartzProperties());
- //注册触发器
- factory.setTriggers(cronJobTrigger);
- return factory;
- }
- /**加载quartz数据源配置,quartz集群时用到
- * @return
- * @author LDX
- * @throws IOException
- */
- // @Bean
- // public Properties quartzProperties() throws IOException {
- // PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
- // propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
- // propertiesFactoryBean.afterPropertiesSet();
- // return propertiesFactoryBean.getObject();
- // }
- /**加载触发器
- * @author LDX
- * @return
- */
- @Bean
- public JobDetailFactoryBean sampleJobDetail() {
- return createJobDetail(ApplicationJob.class);
- }
- /**加载定时器
- * @param jobDetail
- * @param frequency
- * @author LDX
- * @return
- */
- @Bean(name = "cronJobTrigger")
- public CronTriggerFactoryBean sampleJobTrigger(@Qualifier("sampleJobDetail") JobDetail jobDetail,
- @Value("${samplejob.frequency}") long frequency) {
- return createTrigger(jobDetail, frequency);
- }
- /**创建触发器工厂
- * @param jobClass
- * @author LDX
- * @return
- */
- private static JobDetailFactoryBean createJobDetail(Class jobClass) {
- JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
- factoryBean.setJobClass(jobClass);
- factoryBean.setDurability(true);
- return factoryBean;
- }
- /**创建一个以频率为触发节点,以毫秒为单位,可以指定每隔x秒执行任务
- * @param jobDetail
- * @param pollFrequencyMs
- * @author LDX
- * @return
- private static SimpleTriggerFactoryBean createTrigger(JobDetail jobDetail, long pollFrequencyMs) {
- SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
- factoryBean.setJobDetail(jobDetail);
- factoryBean.setStartDelay(0L);
- factoryBean.setRepeatInterval(pollFrequencyMs);
- factoryBean.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
- // in case of misfire, ignore all missed triggers and continue :
- factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT);
- return factoryBean;
- }*/
- /**创建定时器工厂
- * @param jobDetail
- * @param pollFrequencyMs
- * @author LDX
- * @return
- */
- private static CronTriggerFactoryBean createTrigger(JobDetail jobDetail, long pollFrequencyMs) {
- CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
- factoryBean.setJobDetail(jobDetail);
- factoryBean.setStartDelay(0L);
- factoryBean.setCronExpression ("0/5 * * * * ? ");//每5秒执行一次
- return factoryBean;
- }
- package com.xxx.cars.quartz;
- import org.quartz.spi.TriggerFiredBundle;
- import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.ApplicationContextAware;
- import org.springframework.scheduling.quartz.SpringBeanJobFactory;
- public class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory
- implements ApplicationContextAware {
- private transient AutowireCapableBeanFactory beanFactory;
- @Override
- public void setApplicationContext(final ApplicationContext context) {
- beanFactory = context.getAutowireCapableBeanFactory();
- }
- @Override
- protected Object createJobInstance(final TriggerFiredBundle bundle)
- throws Exception {
- final Object job = super.createJobInstance(bundle);
- beanFactory.autowireBean(job);
- return job;
- }
- }
任务调度触发器类
- package com.xxx.cars.quartz;
- import javax.annotation.Resource;
- import org.quartz.Job;
- import org.quartz.JobExecutionContext;
- import org.quartz.JobExecutionException;
- import com.cbkj.sz.cars.entity.ApplicationInfo;
- import com.cbkj.sz.cars.service.ApplicationInfoService;
- import org.springframework.scheduling.quartz.QuartzJobBean;
- /**
- * @author LDX
- *
- */
- public class ApplicationJob implements Job{
- @Resource
- private ApplicationInfoService<ApplicationInfo> applicationInfoService;
- @Override
- public void execute(JobExecutionContext arg0) throws JobExecutionException {
- try {
- applicationInfoService.quartz_text();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- <pre name="code" class="java">@Value("${samplejob.frequency}")
运行项目,任务调度完美运行......