springBoot 集成 Quartz任务调度

来源:互联网 发布:九院吴巍 知乎 编辑:程序博客网 时间:2024/06/14 22:49

由于项目使用spring-boot框架,其框架是为了实现零配置文件去做开发的理念,所以在项目中集成Quartz任务调度并不像spring那样直接配置XML.

首先项目需要用到的jar包:

[html] view plain copy
  1. <dependency>  
  2.             <groupId>org.springframework</groupId>  
  3.             <artifactId>spring-context-support</artifactId>  
  4.             <version>4.1.6.RELEASE</version>  
  5.         </dependency>  
  6. <dependency>  
  7.             <groupId>org.quartz-scheduler</groupId>  
  8.             <artifactId>quartz</artifactId>  
  9.             <version>2.2.1</version>  
  10.         </dependency>  

交给spring管理的bean,代码如下

[java] view plain copy
  1. package com.xxx;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.mybatis.spring.annotation.MapperScan;  
  6. import org.quartz.JobDetail;  
  7. import org.quartz.Trigger;  
  8. import org.quartz.spi.JobFactory;  
  9. import org.springframework.beans.factory.annotation.Qualifier;  
  10. import org.springframework.beans.factory.annotation.Value;  
  11. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;  
  12. import org.springframework.context.ApplicationContext;  
  13. import org.springframework.context.annotation.Bean;  
  14. import org.springframework.context.annotation.ComponentScan;  
  15. import org.springframework.context.annotation.ComponentScan.Filter;  
  16. import org.springframework.context.annotation.Configuration;  
  17. import org.springframework.context.annotation.FilterType;  
  18. import org.springframework.scheduling.annotation.EnableScheduling;  
  19. import org.springframework.scheduling.quartz.CronTriggerFactoryBean;  
  20. import org.springframework.scheduling.quartz.JobDetailFactoryBean;  
  21. import org.springframework.scheduling.quartz.SchedulerFactoryBean;  
  22. import org.springframework.test.context.ContextConfiguration;  
  23. import org.springframework.test.context.web.WebAppConfiguration;  
  24. import org.springframework.transaction.annotation.EnableTransactionManagement;  
  25.   
  26. import com.xxx.base.BaseWebAppConfig;  
  27. import com.xxx.cars.quartz.AutowiringSpringBeanJobFactory;  
  28. import com.xxx.cars.quartz.SampleJob;  
  29.   
  30. @Configuration  
  31. @EnableScheduling  
  32. @ContextConfiguration  
  33. @WebAppConfiguration  
  34. @ComponentScan(basePackages = { "com.xxx" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Configuration.class) })  
  35. @MapperScan("com.xxx.cars.persistence")  
  36. @EnableTransactionManagement  
  37. @EnableAutoConfiguration  
  38. public class WebAppConfig extends BaseWebAppConfig {  
  39.     /** 
  40.      * 配置拦截器 
  41.      *  
  42.      * @author jodie 
  43.      * @param registry 
  44.      */  
  45. //  public void addInterceptors(InterceptorRegistry registry) {  
  46. //      registry.addInterceptor(new UserSecurityInterceptor()).addPathPatterns(  
  47. //              "/**");  
  48. //  }  
  49.       
  50.      @Bean  
  51.         public JobFactory jobFactory(ApplicationContext applicationContext) {  
  52.             AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();  
  53.             jobFactory.setApplicationContext(applicationContext);  
  54.             return jobFactory;  
  55.         }  
  56.   
  57.         /**调度工厂bean  
  58.          * @param jobFactory  
  59.          * @param sampleJobTrigger  
  60.          * @return  
  61.          * @author LDX  
  62.          * @throws IOException  
  63.          */  
  64.         @Bean  
  65.         public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory,  
  66.                                                          @Qualifier("cronJobTrigger") Trigger cronJobTrigger) throws IOException {  
  67.             SchedulerFactoryBean factory = new SchedulerFactoryBean();  
  68.             // this allows to update triggers in DB when updating settings in config file:  
  69.             //用于quartz集群,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了  
  70.             factory.setOverwriteExistingJobs(true);  
  71.           //用于quartz集群,加载quartz数据源  
  72. //          factory.setDataSource(dataSource);  
  73.             factory.setJobFactory(jobFactory);  
  74.             //QuartzScheduler 延时启动,应用启动完20秒后 QuartzScheduler 再启动  
  75.             factory.setStartupDelay(20);  
  76.           //用于quartz集群,加载quartz数据源配置  
  77. //          factory.setQuartzProperties(quartzProperties());  
  78.             //注册触发器  
  79.             factory.setTriggers(cronJobTrigger);  
  80.   
  81.             return factory;  
  82.         }  
  83.   
  84.         /**加载quartz数据源配置,quartz集群时用到 
  85.          * @return 
  86.          * @author LDX 
  87.          * @throws IOException 
  88.          */  
  89. //      @Bean  
  90. //      public Properties quartzProperties() throws IOException {  
  91. //          PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();  
  92. //          propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));  
  93. //          propertiesFactoryBean.afterPropertiesSet();  
  94. //          return propertiesFactoryBean.getObject();  
  95. //      }  
  96.   
  97.         /**加载触发器 
  98.          * @author LDX 
  99.          * @return 
  100.          */  
  101.         @Bean  
  102.         public JobDetailFactoryBean sampleJobDetail() {  
  103.             return createJobDetail(ApplicationJob.class);  
  104.         }  
  105.   
  106.         /**加载定时器 
  107.          * @param jobDetail 
  108.          * @param frequency 
  109.          * @author LDX 
  110.          * @return 
  111.          */  
  112.         @Bean(name = "cronJobTrigger")  
  113.         public CronTriggerFactoryBean sampleJobTrigger(@Qualifier("sampleJobDetail") JobDetail jobDetail,  
  114.                                                          @Value("${samplejob.frequency}"long frequency) {  
  115.             return createTrigger(jobDetail, frequency);  
  116.         }  
  117.   
  118.         /**创建触发器工厂 
  119.          * @param jobClass 
  120.          * @author LDX 
  121.          * @return 
  122.          */  
  123.         private static JobDetailFactoryBean createJobDetail(Class jobClass) {  
  124.             JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();  
  125.             factoryBean.setJobClass(jobClass);  
  126.             factoryBean.setDurability(true);  
  127.             return factoryBean;  
  128.         }  
  129.   
  130.         /**创建一个以频率为触发节点,以毫秒为单位,可以指定每隔x秒执行任务 
  131.          * @param jobDetail 
  132.          * @param pollFrequencyMs 
  133.          * @author LDX 
  134.          * @return 
  135.           
  136.         private static SimpleTriggerFactoryBean createTrigger(JobDetail jobDetail, long pollFrequencyMs) { 
  137.             SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean(); 
  138.             factoryBean.setJobDetail(jobDetail); 
  139.             factoryBean.setStartDelay(0L); 
  140.             factoryBean.setRepeatInterval(pollFrequencyMs); 
  141.             factoryBean.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY); 
  142.             // in case of misfire, ignore all missed triggers and continue : 
  143.             factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT); 
  144.             return factoryBean; 
  145.         }*/  
  146.           
  147.         /**创建定时器工厂 
  148.          * @param jobDetail 
  149.          * @param pollFrequencyMs 
  150.          * @author LDX 
  151.          * @return 
  152.          */  
  153.         private static CronTriggerFactoryBean createTrigger(JobDetail jobDetail, long pollFrequencyMs) {  
  154.             CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();  
  155.             factoryBean.setJobDetail(jobDetail);  
  156.             factoryBean.setStartDelay(0L);  
  157.             factoryBean.setCronExpression ("0/5 * * * * ? ");//每5秒执行一次  
  158.             return factoryBean;  
  159.         }  
  160.           
[java] view plain copy
  1. package com.xxx.cars.quartz;  
  2.   
  3. import org.quartz.spi.TriggerFiredBundle;  
  4. import org.springframework.beans.factory.config.AutowireCapableBeanFactory;  
  5. import org.springframework.context.ApplicationContext;  
  6. import org.springframework.context.ApplicationContextAware;  
  7. import org.springframework.scheduling.quartz.SpringBeanJobFactory;  
  8.   
  9. public class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory  
  10.         implements ApplicationContextAware {  
  11.   
  12.     private transient AutowireCapableBeanFactory beanFactory;  
  13.   
  14.     @Override  
  15.     public void setApplicationContext(final ApplicationContext context) {  
  16.         beanFactory = context.getAutowireCapableBeanFactory();  
  17.     }  
  18.   
  19.     @Override  
  20.     protected Object createJobInstance(final TriggerFiredBundle bundle)  
  21.             throws Exception {  
  22.         final Object job = super.createJobInstance(bundle);  
  23.         beanFactory.autowireBean(job);  
  24.         return job;  
  25.     }  
  26. }  

任务调度触发器类

[java] view plain copy
  1. package com.xxx.cars.quartz;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.quartz.Job;  
  6. import org.quartz.JobExecutionContext;  
  7. import org.quartz.JobExecutionException;  
  8.   
  9. import com.cbkj.sz.cars.entity.ApplicationInfo;  
  10. import com.cbkj.sz.cars.service.ApplicationInfoService;  
  11. import org.springframework.scheduling.quartz.QuartzJobBean;  
  12.   
  13. /** 
  14.  * @author LDX 
  15.  * 
  16.  */  
  17. public class ApplicationJob implements Job{  
  18.   
  19.     @Resource  
  20.     private ApplicationInfoService<ApplicationInfo> applicationInfoService;  
  21.   
  22.     @Override  
  23.     public void execute(JobExecutionContext arg0) throws JobExecutionException {  
  24.         try {  
  25.             applicationInfoService.quartz_text();  
  26.         } catch (Exception e) {  
  27.             e.printStackTrace();  
  28.         }     
  29.           
  30.     }  
  31.   
  32.       
  33.       
  34.       
  35. }   
[java] view plain copy
  1. <pre name="code" class="java">@Value("${samplejob.frequency}")  

这个配置系统配置文件中,本项目使用的是yml配置文件,示例如下


运行项目,任务调度完美运行......

原创粉丝点击