君子博学而日参省乎己 则知明而行无过矣

博客园 首页 新随笔 联系 订阅 管理

如何通过spring 向quartz动态注入service或者,传入动态参数? 
这里主要用到了org.springframework.scheduling.quartz.JobDetailBean这个类的setJobDataAsMap的这个方法!
具体的API如下: 
setJobDataAsMap 
public void setJobDataAsMap(Map jobDataAsMap) 

    Register objects in the JobDataMap via a given Map. 

    These objects will be available to this Job only, in contrast to objects in the SchedulerContext.

   Note: When using persistent Jobs whose JobDetail will be kept in the database, do not put Spring-managed beans or an ApplicationContext reference into the JobDataMap but rather into the SchedulerContext.

    Parameters: 
        jobDataAsMap - Map with String keys and any objects as values (for example Spring-managed beans)
需要注意的是红色的部分,由spring管理的Service无法通过这个方法进行注入, 
spring管理的service 只能放到SchedulerContext里面。 
好的,我们来举个例子。

   

  1. <bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">     
  2.         <property name="dataSource" ref="dataSource" />      
  3.               
  4.         <property name="schedulerContextAsMap">      
  5.             <map>      
  6.                 <!-- spring 管理的service需要放到这里,才能够注入成功 -->      
  7.                 <description>schedulerContextAsMap</description>      
  8.                 <entry key="webSiteService" value-ref="webSiteService"/>      
  9.                 <entry key = "mappingService" value-ref="mappingService"/>      
  10.                 <entry key="detailService" value-ref = "detailService"></entry>     
  11.             </map>      
  12.         </property>      
  13.         <property name="applicationContextSchedulerContextKey" value="applicationContextKey" />     
  14.         <property name="configLocation" value="classpath:quartz.properties" />     
  15.     </bean>      
  16.           
  17.     <bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">     
  18.         <property name="jobClass" value = "com.fangjia.dc.quartz.MyQuartzJob"/>     
  19.         <property name="jobDataAsMap">      
  20.             <map>      
  21.                 <!-- 非spring管理的service放到这里,就可以注入进去 -->      
  22.                 <description>jobDataAsMap</description>      
  23.                 <!-- key 属性值,value 对应的bean -->      
  24.                 <entry key="uploader" value-ref="uploader" />      
  25.             </map>      
  26.         </property>      
  27.     </bean>   

 

这里一共注入了 bean,分别是webSiteService,mappingService,detailService和uploader,然后在MyQuartzJob中使用注入的service 

 

  1. public class MyQuartzJob extends QuartzJobBean {     
  2.     
  3.     private static final Logger logger = Logger.getLogger(MyQuartzJob.class);     
  4.     private Uploader uploader;       
  5.     private IService<WebSite> webSiteService;     
  6.     private IService<Mapping> mappingService;     
  7.     private IService<MappingDetail> detailService;     
  8.          
  9.     @Override    
  10.     protected void executeInternal(JobExecutionContext context) throws JobExecutionException {    
  11.              
  12.         try {     
  13.             //获取JobExecutionContext中的service对象    
  14.             SchedulerContext skedCtx = context.getScheduler().getContext();     
  15.             //获取SchedulerContext中的service    
  16.             //这里的service就是通过配置文件 配置的    
  17.             webSiteService = (IService<WebSite>)skedCtx.get("webSiteService");     
  18.             mappingService = (IService<Mapping>)skedCtx.get("mappingService");     
  19.             detailService = (IService<MappingDetail>)skedCtx.get("detailService");    
  20.                  
  21.             //获取 当前的trigger 名称,    
  22.             Trigger trigger = context.getTrigger();     
  23.             String name = trigger.getName();     
  24.     
  25.             //从trigger中的jobDataMap中获取uploader    
  26.             uploader = (Uploader) context.getJobDetail.getJobDataMap().get("uploader");     
  27.     
  28.             WebSite webSite = webSiteService.findByName(name);     
  29.             logger.info("webSite id:" + webSite.getId());     
  30.             loadMappingConfiguration(webSite);     
  31.             uploader.process(webSite, typeXpathFiels, domainMap);     
  32.         } catch (SchedulerException e) {     
  33.             e.printStackTrace();     
  34.         } catch (Exception e) {     
  35.             e.printStackTrace();     
  36.         }     
  37.              
  38.     }     
  39.     //属性的 get set方法    
  40. }    

定时任务的动态管理,没有配置的spring文件中 
采用页面传值,实现quartz定时任务的CRUD

 

  1. public void schedule(String name, CronExpression cronExpression,String group) throws SchedulerException {    
  2.              
  3.         //添加Job 给scheduler,允许 replace    
  4.              
  5.         jobDetail.setRequestsRecovery(true);     
  6.         //孤立线程 不再保存在DB中    
  7.         jobDetail.setDurability(false);     
  8.         jobDetail.setName(name);     
  9.         logger.info(" is  durable:" + jobDetail.isDurable());     
  10.         //设置replace为true,相同名字的job存在,则替换    
  11.         scheduler.addJob(jobDetail, true);     
  12.              
  13.         CronTrigger cronTrigger = new CronTrigger(name, group, jobDetail.getName(), Scheduler.DEFAULT_GROUP);    
  14.         cronTrigger.setCronExpression(cronExpression);     
  15.         scheduler.scheduleJob(cronTrigger);     
  16.         scheduler.rescheduleJob(cronTrigger.getName(), cronTrigger.getGroup(), cronTrigger);    
  17.     }     
  18.     
  19.     public void pauseTrigger(String triggerName, String group) throws SchedulerException {    
  20.         logger.info("pause triggerName:" + triggerName);     
  21.         scheduler.pauseTrigger(triggerName, group);     
  22.     }     
  23.     
  24.     public void resumeTrigger(String triggerName, String group) throws SchedulerException {    
  25.         logger.info("resume trigger:" + triggerName + " group:" + group);     
  26.         scheduler.resumeTrigger(triggerName, group);     
  27.     }     
  28.     
  29.     public boolean removeTrigdger(String triggerName, String group) throws SchedulerException {    
  30.         scheduler.pauseTrigger(triggerName, group);     
  31.         return scheduler.unscheduleJob(triggerName, group);     
  32.     }    

 

 quartz.properties设置

  

  1. org.quartz.scheduler.instanceName = DefaultQuartzScheduler     
  2. org.quartz.scheduler.rmi.export = false    
  3. org.quartz.scheduler.rmi.proxy = false    
  4. org.quartz.scheduler.wrapJobExecutionInUserTransaction = false    
  5.     
  6. org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool     
  7. org.quartz.threadPool.threadCount = 10    
  8. org.quartz.threadPool.threadPriority = 5    
  9. org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true   
  10.     
  11. org.quartz.jobStore.misfireThreshold = 60000    
  12.     
  13. #org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore     
  14.     
  15. org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX     
  16. org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate    
  17. org.quartz.jobStore.tablePrefix = QRTZ_       
  18. org.quartz.jobStore.isClustered = false       
  19. org.quartz.jobStore.maxMisfiresToHandleAtATime=1      
  20. #org.quartz.jobStore.txIsolationLevelReadCommitted = true 
posted on 2012-11-28 23:50  刺猬的温驯  阅读(762)  评论(0编辑  收藏  举报