Quartz与Spring集成——创建调度器 定时

来源:互联网 发布:java程序设计步骤 编辑:程序博客网 时间:2024/05/16 10:59

目录(?)[-]

  1. 前言
  2. 创建调度器
    1. 读取调度器配置
    2. 创建远端调度器代理
    3. 创建远端jmx调度器代理
    4. 实例化作业工厂
    5. 实例化实例ID生成器
    6. 实例化线程池
    7. 实例化JobStore的具体实例
    8. 获取数据库管理器并设置数据库连接池
    9. 设置调度器插件
    10. 设置作业监听器
    11. 设置触发器监听器
    12. 获取线程执行器
    13. 创建脚本执行工厂
    14. 生成调度实例ID
    15. 设置JobStore的数据库错误重试的间隔及现场执行器
    16. 构造QuartzSchedulerResources
    17. 构造QuartzScheduler
      1. 构造QuartzSchedulerThread
      2. 阻止QuartzSchedulerThread的执行
    18. 创建调度器
    19. 其他处理
  3. 总结

http://blog.csdn.net/beliefer/article/details/52094198

前言

在《Quartz与Spring集成—— SchedulerFactoryBean的初始化分析》一文中介绍过Spring集成Quartz时的初始化过程,其中简单的提到了创建调度器的方法createScheduler。本文将着重介绍Quartz初始化时是如何创建调度器的。

创建调度器

这里从createScheduler的实现(见代码清单1)来分析,其处理步骤如下:

  1. 设置线程上下文的类加载器;
  2. 通过单例方法获取SchedulerRepository的实例(见代码清单2);
  3. 从调度仓库实例SchedulerRepository中查找已经存在的调度器,这里想说的是虽然此实现考虑到了多线程安全问题,不过这种方式效率较低。不如提前初始化,由final修饰,不使用同步语句,避免线程间的阻塞和等待;
  4. 获取调取器(见代码清单3),其实际上首先从调度器缓存中查找调度器,否则调用instantiate方法创建调度器;
  5. 检查重新获取的调度器和已经存在的调度器是否相同,如果相同则说明此调度器已经被激活了,将会报出异常。如果调度器是首次被激活,那么将返回此调度器。这里的实现稍微有些拖沓,其实只有当existingScheduler为null时,才会调用instantiate方法创建newScheduler,也只有在这个时候newScheduler才不等于existingScheduler,并且不会抛出异常。因此我们甚至可以省去Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null);这行代码,而直接将代码清单3中的实现进行修改——当sched为null时才调用instantiate方法创建调度器。

代码清单1

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName)  
  2.         throws SchedulerException {  
  3.   
  4.     // Override thread context ClassLoader to work around naive Quartz ClassLoadHelper loading.  
  5.     Thread currentThread = Thread.currentThread();  
  6.     ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();  
  7.     boolean overrideClassLoader = (this.resourceLoader != null &&  
  8.             !this.resourceLoader.getClassLoader().equals(threadContextClassLoader));  
  9.     if (overrideClassLoader) {  
  10.         currentThread.setContextClassLoader(this.resourceLoader.getClassLoader());  
  11.     }  
  12.     try {  
  13.         SchedulerRepository repository = SchedulerRepository.getInstance();  
  14.         synchronized (repository) {  
  15.             Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null);  
  16.             Scheduler newScheduler = schedulerFactory.getScheduler();  
  17.             if (newScheduler == existingScheduler) {  
  18.                 throw new IllegalStateException("Active Scheduler of name '" + schedulerName + "' already registered " +  
  19.                         "in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!");  
  20.             }  
  21.             if (!this.exposeSchedulerInRepository) {  
  22.                 // Need to remove it in this case, since Quartz shares the Scheduler instance by default!  
  23.                 SchedulerRepository.getInstance().remove(newScheduler.getSchedulerName());  
  24.             }  
  25.             return newScheduler;  
  26.         }  
  27.     }  
  28.     finally {  
  29.         if (overrideClassLoader) {  
  30.             // Reset original thread context ClassLoader.  
  31.             currentThread.setContextClassLoader(threadContextClassLoader);  
  32.         }  
  33.     }  
  34. }  

代码清单2

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static synchronized SchedulerRepository getInstance() {  
  2.     if (inst == null) {  
  3.         inst = new SchedulerRepository();  
  4.     }  
  5.   
  6.     return inst;  
  7. }  

代码清单3
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public Scheduler getScheduler() throws SchedulerException {  
  2.     if (cfg == null) {  
  3.         initialize();  
  4.     }  
  5.   
  6.     SchedulerRepository schedRep = SchedulerRepository.getInstance();  
  7.   
  8.     Scheduler sched = schedRep.lookup(getSchedulerName());  
  9.   
  10.     if (sched != null) {  
  11.         if (sched.isShutdown()) {  
  12.             schedRep.remove(getSchedulerName());  
  13.         } else {  
  14.             return sched;  
  15.         }  
  16.     }  
  17.   
  18.     sched = instantiate();  
  19.   
  20.     return sched;  
  21. }  

读取调度器配置

instantiate方法中包含了很多从PropertiesParser(PropertiesParser在《Quartz与Spring集成—— SchedulerFactoryBean的初始化分析》一文中介绍过)中获取各种属性的语句,这里不过多展示。重点来看其更为本质的内容。

创建远端调度器代理

如果当前调度器实际是代理远程RMI调度器,那么创建RemoteScheduler,并将当前调取器与RemoteScheduler进行绑定,最后以此RemoteScheduler作为调度器,见代码清单4。

代码清单4

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. if (rmiProxy) {  
  2.   
  3.     if (autoId) {  
  4.         schedInstId = DEFAULT_INSTANCE_ID;  
  5.     }  
  6.   
  7.     String uid = (rmiBindName == null) ? QuartzSchedulerResources.getUniqueIdentifier(  
  8.             schedName, schedInstId) : rmiBindName;  
  9.   
  10.     RemoteScheduler remoteScheduler = new RemoteScheduler(uid, rmiHost, rmiPort);  
  11.   
  12.     schedRep.bind(remoteScheduler);  
  13.   
  14.     return remoteScheduler;  
  15. }  

创建远端jmx调度器代理

如果当前调度器实际是代理远程JMX调度器,那么创建RemoteMBeanScheduler,并将当前调度器与RemoteMBeanScheduler进行绑定,最后以此RemoteMBeanScheduler作为调度器,见代码清单5。

代码清单5

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. if (jmxProxy) {  
  2.     if (autoId) {  
  3.         schedInstId = DEFAULT_INSTANCE_ID;  
  4.     }  
  5.   
  6.     if (jmxProxyClass == null) {  
  7.         throw new SchedulerConfigException("No JMX Proxy Scheduler class provided");  
  8.     }  
  9.   
  10.     RemoteMBeanScheduler jmxScheduler = null;  
  11.     try {  
  12.         jmxScheduler = (RemoteMBeanScheduler)loadHelper.loadClass(jmxProxyClass)  
  13.                 .newInstance();  
  14.     } catch (Exception e) {  
  15.         throw new SchedulerConfigException(  
  16.                 "Unable to instantiate RemoteMBeanScheduler class.", e);  
  17.     }  
  18.   
  19.     if (jmxObjectName == null) {  
  20.         jmxObjectName = QuartzSchedulerResources.generateJMXObjectName(schedName, schedInstId);  
  21.     }  
  22.   
  23.     jmxScheduler.setSchedulerObjectName(jmxObjectName);  
  24.   
  25.     tProps = cfg.getPropertyGroup(PROP_SCHED_JMX_PROXY, true);  
  26.     try {  
  27.         setBeanProps(jmxScheduler, tProps);  
  28.     } catch (Exception e) {  
  29.         initException = new SchedulerException("RemoteMBeanScheduler class '"  
  30.                 + jmxProxyClass + "' props could not be configured.", e);  
  31.         throw initException;  
  32.     }  
  33.   
  34.     jmxScheduler.initialize();  
  35.   
  36.     schedRep.bind(jmxScheduler);  
  37.   
  38.     return jmxScheduler;  
  39. }  

实例化作业工厂

如果指定了jobFactoryClass属性,那么实例化作业工厂实例,见代码清单6。实例化的JobFactory将用于创建调度作业。

代码清单6

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. JobFactory jobFactory = null;  
  2. if(jobFactoryClass != null) {  
  3.     try {  
  4.         jobFactory = (JobFactory) loadHelper.loadClass(jobFactoryClass)  
  5.                 .newInstance();  
  6.     } catch (Exception e) {  
  7.         throw new SchedulerConfigException(  
  8.                 "Unable to instantiate JobFactory class: "  
  9.                         + e.getMessage(), e);  
  10.     }  
  11.   
  12.     tProps = cfg.getPropertyGroup(PROP_SCHED_JOB_FACTORY_PREFIX, true);  
  13.     try {  
  14.         setBeanProps(jobFactory, tProps);  
  15.     } catch (Exception e) {  
  16.         initException = new SchedulerException("JobFactory class '"  
  17.                 + jobFactoryClass + "' props could not be configured.", e);  
  18.         throw initException;  
  19.     }  
  20. }  

实例化实例ID生成器

如果指定了instanceIdGeneratorClass属性,那么实例化实例ID生成器,见代码清单7。此生成器用来给调度器实例生成ID。

代码清单7

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. InstanceIdGenerator instanceIdGenerator = null;  
  2. if(instanceIdGeneratorClass != null) {  
  3.     try {  
  4.         instanceIdGenerator = (InstanceIdGenerator) loadHelper.loadClass(instanceIdGeneratorClass)  
  5.             .newInstance();  
  6.     } catch (Exception e) {  
  7.         throw new SchedulerConfigException(  
  8.                 "Unable to instantiate InstanceIdGenerator class: "  
  9.                 + e.getMessage(), e);  
  10.     }  
  11.   
  12.     tProps = cfg.getPropertyGroup(PROP_SCHED_INSTANCE_ID_GENERATOR_PREFIX, true);  
  13.     try {  
  14.         setBeanProps(instanceIdGenerator, tProps);  
  15.     } catch (Exception e) {  
  16.         initException = new SchedulerException("InstanceIdGenerator class '"  
  17.                 + instanceIdGeneratorClass + "' props could not be configured.", e);  
  18.         throw initException;  
  19.     }  
  20. }  

实例化线程池

org.quartz.threadPool.class属性用于指定线程池类,如果没有指定,则默认为org.quartz.simpl.SimpleThreadPool,见代码清单8。此线程池将用于shell作业的执行。

代码清单8

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. String tpClass = cfg.getStringProperty(PROP_THREAD_POOL_CLASS, SimpleThreadPool.class.getName());  
  2.   
  3. if (tpClass == null) {  
  4.     initException = new SchedulerException(  
  5.             "ThreadPool class not specified. ");  
  6.     throw initException;  
  7. }  
  8.   
  9. try {  
  10.     tp = (ThreadPool) loadHelper.loadClass(tpClass).newInstance();  
  11. catch (Exception e) {  
  12.     initException = new SchedulerException("ThreadPool class '"  
  13.             + tpClass + "' could not be instantiated.", e);  
  14.     throw initException;  
  15. }  
  16. tProps = cfg.getPropertyGroup(PROP_THREAD_POOL_PREFIX, true);  
  17. try {  
  18.     setBeanProps(tp, tProps);  
  19. catch (Exception e) {  
  20.     initException = new SchedulerException("ThreadPool class '"  
  21.             + tpClass + "' props could not be configured.", e);  
  22.     throw initException;  
  23. }  

实例化JobStore的具体实例

org.quartz.jobStore.class属性用于指定JobStore的具体类型,我显示指定了org.springframework.scheduling.quartz.LocalDataSourceJobStore,如果没有指定,则默认为RAMJobStore,见代码清单9。jobStore顾名思义,就是作业的存储,以LocalDataSourceJobStore为例,将通过它对触发器、作业等内容进行增删改查。

代码清单9

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. String jsClass = cfg.getStringProperty(PROP_JOB_STORE_CLASS,  
  2.         RAMJobStore.class.getName());  
  3.   
  4. if (jsClass == null) {  
  5.     initException = new SchedulerException(  
  6.             "JobStore class not specified. ");  
  7.     throw initException;  
  8. }  
  9.   
  10. try {  
  11.     js = (JobStore) loadHelper.loadClass(jsClass).newInstance();  
  12. catch (Exception e) {  
  13.     initException = new SchedulerException("JobStore class '" + jsClass  
  14.             + "' could not be instantiated.", e);  
  15.     throw initException;  
  16. }  
  17.   
  18. SchedulerDetailsSetter.setDetails(js, schedName, schedInstId);  
  19.   
  20. tProps = cfg.getPropertyGroup(PROP_JOB_STORE_PREFIX, truenew String[] {PROP_JOB_STORE_LOCK_HANDLER_PREFIX});  
  21. try {  
  22.     setBeanProps(js, tProps);  
  23. catch (Exception e) {  
  24.     initException = new SchedulerException("JobStore class '" + jsClass  
  25.             + "' props could not be configured.", e);  
  26.     throw initException;  
  27. }  

获取数据库管理器并设置数据库连接池

这一步骤的执行逻辑比较多,但是仔细整理后发现数据库管理器都一样,无非是数据连接池的提供者不同(见代码清单10),一共分为三种:

方式一:连接池提供者由connectionProvider.class属性指定;

方式二:连接池提供者由jndiURL属性指定;

方式三:连接池提供者为PoolingConnectionProvider,其使用了C3P0连接池;

代码清单10

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. String[] dsNames = cfg.getPropertyGroups(PROP_DATASOURCE_PREFIX);  
  2. for (int i = 0; i < dsNames.length; i++) {  
  3.     PropertiesParser pp = new PropertiesParser(cfg.getPropertyGroup(  
  4.             PROP_DATASOURCE_PREFIX + "." + dsNames[i], true));  
  5.   
  6.     String cpClass = pp.getStringProperty(PROP_CONNECTION_PROVIDER_CLASS, null);  
  7.   
  8.     // custom connectionProvider...  
  9.     if(cpClass != null) {  
  10.         ConnectionProvider cp = null;  
  11.         try {  
  12.             cp = (ConnectionProvider) loadHelper.loadClass(cpClass).newInstance();  
  13.         } catch (Exception e) {  
  14.             initException = new SchedulerException("ConnectionProvider class '" + cpClass  
  15.                     + "' could not be instantiated.", e);  
  16.             throw initException;  
  17.         }  
  18.   
  19.         try {  
  20.             // remove the class name, so it isn't attempted to be set  
  21.             pp.getUnderlyingProperties().remove(  
  22.                     PROP_CONNECTION_PROVIDER_CLASS);  
  23.   
  24.             if (cp instanceof PoolingConnectionProvider) {  
  25.                 populateProviderWithExtraProps((PoolingConnectionProvider)cp, pp.getUnderlyingProperties());  
  26.             } else {  
  27.                 setBeanProps(cp, pp.getUnderlyingProperties());  
  28.             }  
  29.             cp.initialize();  
  30.         } catch (Exception e) {  
  31.             initException = new SchedulerException("ConnectionProvider class '" + cpClass  
  32.                     + "' props could not be configured.", e);  
  33.             throw initException;  
  34.         }  
  35.   
  36.         dbMgr = DBConnectionManager.getInstance();  
  37.         dbMgr.addConnectionProvider(dsNames[i], cp);  
  38.     } else {  
  39.         String dsJndi = pp.getStringProperty(PROP_DATASOURCE_JNDI_URL, null);  
  40.   
  41.         if (dsJndi != null) {  
  42.             boolean dsAlwaysLookup = pp.getBooleanProperty(  
  43.                     PROP_DATASOURCE_JNDI_ALWAYS_LOOKUP);  
  44.             String dsJndiInitial = pp.getStringProperty(  
  45.                     PROP_DATASOURCE_JNDI_INITIAL);  
  46.             String dsJndiProvider = pp.getStringProperty(  
  47.                     PROP_DATASOURCE_JNDI_PROVDER);  
  48.             String dsJndiPrincipal = pp.getStringProperty(  
  49.                     PROP_DATASOURCE_JNDI_PRINCIPAL);  
  50.             String dsJndiCredentials = pp.getStringProperty(  
  51.                     PROP_DATASOURCE_JNDI_CREDENTIALS);  
  52.             Properties props = null;  
  53.             if (null != dsJndiInitial || null != dsJndiProvider  
  54.                     || null != dsJndiPrincipal || null != dsJndiCredentials) {  
  55.                 props = new Properties();  
  56.                 if (dsJndiInitial != null) {  
  57.                     props.put(PROP_DATASOURCE_JNDI_INITIAL,  
  58.                             dsJndiInitial);  
  59.                 }  
  60.                 if (dsJndiProvider != null) {  
  61.                     props.put(PROP_DATASOURCE_JNDI_PROVDER,  
  62.                             dsJndiProvider);  
  63.                 }  
  64.                 if (dsJndiPrincipal != null) {  
  65.                     props.put(PROP_DATASOURCE_JNDI_PRINCIPAL,  
  66.                             dsJndiPrincipal);  
  67.                 }  
  68.                 if (dsJndiCredentials != null) {  
  69.                     props.put(PROP_DATASOURCE_JNDI_CREDENTIALS,  
  70.                             dsJndiCredentials);  
  71.                 }  
  72.             }  
  73.             JNDIConnectionProvider cp = new JNDIConnectionProvider(dsJndi,  
  74.                     props, dsAlwaysLookup);  
  75.             dbMgr = DBConnectionManager.getInstance();  
  76.             dbMgr.addConnectionProvider(dsNames[i], cp);  
  77.         } else {  
  78.             String dsDriver = pp.getStringProperty(PoolingConnectionProvider.DB_DRIVER);  
  79.             String dsURL = pp.getStringProperty(PoolingConnectionProvider.DB_URL);  
  80.   
  81.             if (dsDriver == null) {  
  82.                 initException = new SchedulerException(  
  83.                         "Driver not specified for DataSource: "  
  84.                                 + dsNames[i]);  
  85.                 throw initException;  
  86.             }  
  87.             if (dsURL == null) {  
  88.                 initException = new SchedulerException(  
  89.                         "DB URL not specified for DataSource: "  
  90.                                 + dsNames[i]);  
  91.                 throw initException;  
  92.             }  
  93.             try {  
  94.                 PoolingConnectionProvider cp = new PoolingConnectionProvider(pp.getUnderlyingProperties());  
  95.                 dbMgr = DBConnectionManager.getInstance();  
  96.                 dbMgr.addConnectionProvider(dsNames[i], cp);  
  97.   
  98.                 // Populate the underlying C3P0 data source pool properties  
  99.                 populateProviderWithExtraProps(cp, pp.getUnderlyingProperties());  
  100.             } catch (Exception sqle) {  
  101.                 initException = new SchedulerException(  
  102.                         "Could not initialize DataSource: " + dsNames[i],  
  103.                         sqle);  
  104.                 throw initException;  
  105.             }  
  106.         }  
  107.   
  108.     }  
  109.   
  110. }  

设置调度器插件

这一段用于设置各种调度器插件,见代码清单11。这里的PROP_PLUGIN_PREFIX的值为org.quartz.plugin,即可以在Quartz的属性文件中配置一系列以org.quartz.plugin为前缀的插件,例如可以在关闭JVM时,添加钩子做一些清理工作的插件org.quartz.plugins.management.ShutdownHookPlugin。

代码清单11

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. String[] pluginNames = cfg.getPropertyGroups(PROP_PLUGIN_PREFIX);  
  2. SchedulerPlugin[] plugins = new SchedulerPlugin[pluginNames.length];  
  3. for (int i = 0; i < pluginNames.length; i++) {  
  4.     Properties pp = cfg.getPropertyGroup(PROP_PLUGIN_PREFIX + "."  
  5.             + pluginNames[i], true);  
  6.   
  7.     String plugInClass = pp.getProperty(PROP_PLUGIN_CLASS, null);  
  8.   
  9.     if (plugInClass == null) {  
  10.         initException = new SchedulerException(  
  11.                 "SchedulerPlugin class not specified for plugin '"  
  12.                         + pluginNames[i] + "'");  
  13.         throw initException;  
  14.     }  
  15.     SchedulerPlugin plugin = null;  
  16.     try {  
  17.         plugin = (SchedulerPlugin)  
  18.                 loadHelper.loadClass(plugInClass).newInstance();  
  19.     } catch (Exception e) {  
  20.         initException = new SchedulerException(  
  21.                 "SchedulerPlugin class '" + plugInClass  
  22.                         + "' could not be instantiated.", e);  
  23.         throw initException;  
  24.     }  
  25.     try {  
  26.         setBeanProps(plugin, pp);  
  27.     } catch (Exception e) {  
  28.         initException = new SchedulerException(  
  29.                 "JobStore SchedulerPlugin '" + plugInClass  
  30.                         + "' props could not be configured.", e);  
  31.         throw initException;  
  32.     }  
  33.   
  34.     plugins[i] = plugin;  
  35. }  

设置作业监听器

这一步用于设置作业监听器,我觉得可以用于做一些作业监控相关的扩展,见代明清单12。这里的常量PROP_JOB_LISTENER_PREFIX的值为org.quartz.jobListener。我们可以在Quartz属性文件添加以org.quartz.jobListener为前缀的作业监听器。

代明清单12

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Class<?>[] strArg = new Class[] { String.class };  
  2. String[] jobListenerNames = cfg.getPropertyGroups(PROP_JOB_LISTENER_PREFIX);  
  3. JobListener[] jobListeners = new JobListener[jobListenerNames.length];  
  4. for (int i = 0; i < jobListenerNames.length; i++) {  
  5.     Properties lp = cfg.getPropertyGroup(PROP_JOB_LISTENER_PREFIX + "."  
  6.             + jobListenerNames[i], true);  
  7.   
  8.     String listenerClass = lp.getProperty(PROP_LISTENER_CLASS, null);  
  9.   
  10.     if (listenerClass == null) {  
  11.         initException = new SchedulerException(  
  12.                 "JobListener class not specified for listener '"  
  13.                         + jobListenerNames[i] + "'");  
  14.         throw initException;  
  15.     }  
  16.     JobListener listener = null;  
  17.     try {  
  18.         listener = (JobListener)  
  19.                loadHelper.loadClass(listenerClass).newInstance();  
  20.     } catch (Exception e) {  
  21.         initException = new SchedulerException(  
  22.                 "JobListener class '" + listenerClass  
  23.                         + "' could not be instantiated.", e);  
  24.         throw initException;  
  25.     }  
  26.     try {  
  27.         Method nameSetter = null;  
  28.         try {   
  29.             nameSetter = listener.getClass().getMethod("setName", strArg);  
  30.         }  
  31.         catch(NoSuchMethodException ignore) {   
  32.             /* do nothing */   
  33.         }  
  34.         if(nameSetter != null) {  
  35.             nameSetter.invoke(listener, new Object[] {jobListenerNames[i] } );  
  36.         }  
  37.         setBeanProps(listener, lp);  
  38.     } catch (Exception e) {  
  39.         initException = new SchedulerException(  
  40.                 "JobListener '" + listenerClass  
  41.                         + "' props could not be configured.", e);  
  42.         throw initException;  
  43.     }  
  44.     jobListeners[i] = listener;  
  45. }  

设置触发器监听器

这一步设置触发器监听器,见代码清单13。与作业监听器类似,不再赘述。

代码清单13

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. String[] triggerListenerNames = cfg.getPropertyGroups(PROP_TRIGGER_LISTENER_PREFIX);  
  2. TriggerListener[] triggerListeners = new TriggerListener[triggerListenerNames.length];  
  3. for (int i = 0; i < triggerListenerNames.length; i++) {  
  4.     Properties lp = cfg.getPropertyGroup(PROP_TRIGGER_LISTENER_PREFIX + "."  
  5.             + triggerListenerNames[i], true);  
  6.   
  7.     String listenerClass = lp.getProperty(PROP_LISTENER_CLASS, null);  
  8.   
  9.     if (listenerClass == null) {  
  10.         initException = new SchedulerException(  
  11.                 "TriggerListener class not specified for listener '"  
  12.                         + triggerListenerNames[i] + "'");  
  13.         throw initException;  
  14.     }  
  15.     TriggerListener listener = null;  
  16.     try {  
  17.         listener = (TriggerListener)  
  18.                loadHelper.loadClass(listenerClass).newInstance();  
  19.     } catch (Exception e) {  
  20.         initException = new SchedulerException(  
  21.                 "TriggerListener class '" + listenerClass  
  22.                         + "' could not be instantiated.", e);  
  23.         throw initException;  
  24.     }  
  25.     try {  
  26.         Method nameSetter = null;  
  27.         try {   
  28.             nameSetter = listener.getClass().getMethod("setName", strArg);  
  29.         }  
  30.         catch(NoSuchMethodException ignore) { /* do nothing */ }  
  31.         if(nameSetter != null) {  
  32.             nameSetter.invoke(listener, new Object[] {triggerListenerNames[i] } );  
  33.         }  
  34.         setBeanProps(listener, lp);  
  35.     } catch (Exception e) {  
  36.         initException = new SchedulerException(  
  37.                 "TriggerListener '" + listenerClass  
  38.                         + "' props could not be configured.", e);  
  39.         throw initException;  
  40.     }  
  41.     triggerListeners[i] = listener;  
  42. }  

获取线程执行器

可以通过属性org.quartz.threadExecutor.class设置线程执行器,如果没有指定,默认为DefaultThreadExecutor,见代码清单13。此线程执行器用于执行定时调度线程QuartzSchedulerThread(有关QuartzSchedulerThread的执行过程将会在单独的博文中展开)。

代码清单13

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. String threadExecutorClass = cfg.getStringProperty(PROP_THREAD_EXECUTOR_CLASS);  
  2. if (threadExecutorClass != null) {  
  3.     tProps = cfg.getPropertyGroup(PROP_THREAD_EXECUTOR, true);  
  4.     try {  
  5.         threadExecutor = (ThreadExecutor) loadHelper.loadClass(threadExecutorClass).newInstance();  
  6.         log.info("Using custom implementation for ThreadExecutor: " + threadExecutorClass);  
  7.   
  8.         setBeanProps(threadExecutor, tProps);  
  9.     } catch (Exception e) {  
  10.         initException = new SchedulerException(  
  11.                 "ThreadExecutor class '" + threadExecutorClass + "' could not be instantiated.", e);  
  12.         throw initException;  
  13.     }  
  14. else {  
  15.     log.info("Using default implementation for ThreadExecutor");  
  16.     threadExecutor = new DefaultThreadExecutor();  
  17. }  

创建脚本执行工厂

如果需要作业运行在事务中(可以通过属性org.quartz.scheduler.wrapJobExecutionInUserTransaction指定),则创建JTAJobRunShellFactory,否则创建JTAAnnotationAwareJobRunShellFactory,见代码清单14。JobRunShellFactory将用于生成作业的shell执行对象JobRunShell。

代码清单14

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. JobRunShellFactory jrsf = null// Create correct run-shell factory...  
  2.   
  3. if (userTXLocation != null) {  
  4.     UserTransactionHelper.setUserTxLocation(userTXLocation);  
  5. }  
  6.   
  7. if (wrapJobInTx) {  
  8.     jrsf = new JTAJobRunShellFactory();  
  9. else {  
  10.     jrsf = new JTAAnnotationAwareJobRunShellFactory();  
  11. }  

生成调度实例ID

如果需要自动生成调度实例ID(可以通过属性org.quartz.scheduler.instanceId为AUTO或者SYS_PROP,其中当指定为AUTO时,则instanceIdGeneratorClass由org.quartz.scheduler.instanceIdGenerator.class属性指定,默认为org.quartz.simpl.SimpleInstanceIdGenerator;当指定为SYS_PROP,则instanceIdGeneratorClass等于org.quartz.simpl.SystemPropertyInstanceIdGenerator),那么调度实例ID为NON_CLUSTERED,当JobStore支持集群部署,那么调度实例ID将由调度实例ID生成器instanceIdGenerator产生,见代码清单15。(注:当不需要自动生成调度实例ID时,可以通过属性org.quartz.scheduler.instanceId指定)

代码清单15

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. if (autoId) {  
  2.     try {  
  3.       schedInstId = DEFAULT_INSTANCE_ID;  
  4.       if (js.isClustered()) {  
  5.           schedInstId = instanceIdGenerator.generateInstanceId();  
  6.       }  
  7.     } catch (Exception e) {  
  8.         getLog().error("Couldn't generate instance Id!", e);  
  9.         throw new IllegalStateException("Cannot run without an instance id.");  
  10.     }  
  11. }  

设置JobStore的数据库错误重试的间隔及现场执行器

JobStoreSupport是JobStore的抽象实现类,只有继承自JobStoreSupport的具体实现类(例如org.springframework.scheduling.quartz.LocalDataSourceJobStore)才可以通过调用其setDbRetryInterval方法设置数据库错误重试间隔(dbFailureRetry属性默认为15000,也可以通过设置org.quartz.scheduler.dbFailureRetryInterval属性进行指定),setThreadExecutor方法用于设置JobStoreSupport的线程执行器,见代码清单16。

代码清单16

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. if (js instanceof JobStoreSupport) {  
  2.     JobStoreSupport jjs = (JobStoreSupport)js;  
  3.     jjs.setDbRetryInterval(dbFailureRetry);  
  4.     if(threadsInheritInitalizersClassLoader)  
  5.         jjs.setThreadsInheritInitializersClassLoadContext(threadsInheritInitalizersClassLoader);  
  6.       
  7.     jjs.setThreadExecutor(threadExecutor);  
  8. }  

构造QuartzSchedulerResources

QuartzSchedulerResources用于持有定时调度需要的各种资源,如作业运行脚本的工厂、执行QuartzSchedulerThread的线程执行器、执行具体shell作业的线程池、各种插件、监听器等。在构造QuartzSchedulerResources的过程中(见代码清单17),设置了很多属性,现在列举如下:

属性名称含义备注name调度名称可以由org.quartz.scheduler.instanceName属性指定threadName调度线程名称可以由org.quartz.scheduler.threadName属性指定,默认等于调度名称加后缀_QuartzSchedulerThread产生instanceId调度实例ID可以由org.quartz.scheduler.instanceId属性指定,具体生成规则见文中描述jobRunShellFactory创建作业运行脚本工厂可以由org.quartz.scheduler.wrapJobExecutionInUserTransaction属性指定,具体实现有JTAJobRunShellFactory和JTAAnnotationAwareJobRunShellFactory两种makeSchedulerThreadDaemon调度线程是否是后台线程可以由org.quartz.scheduler.makeSchedulerThreadDaemon属性指定threadsInheritInitalizersClassLoader线程是否继承初始化的类加载器可以由org.quartz.scheduler.threadsInheritContextClassLoaderOfInitializer属性指定runUpdateCheck运行时是否检查Quartz的可用更新版本可以由org.quartz.scheduler.skipUpdateCheck属性指定,runUpdateCheck与指定值相反batchTimeWindow在时间窗口前批量触发可以由org.quartz.scheduler.batchTriggerAcquisitionFireAheadTimeWindow属性指定maxBatchSize最大批量执行的作业数可以由org.quartz.scheduler.batchTriggerAcquisitionMaxCount属性指定interruptJobsOnShutdown当关闭作业时,中断作业线程可以由org.quartz.scheduler.interruptJobsOnShutdown属性指定interruptJobsOnShutdownWithWait当关闭作业时,等待中断作业线程可以由org.quartz.scheduler.interruptJobsOnShutdownWithWait属性指定threadExecutor线程执行器可以由org.quartz.threadExecutor.class属性指定,默认为DefaultThreadExecutorthreadPool线程池可以由org.quartz.threadPool.class属性指定,默认为SimpleThreadPooljobStore作业存储可以由org.quartz.jobStore.class属性指定,默认为RAMJobStore


代码清单17

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. QuartzSchedulerResources rsrcs = new QuartzSchedulerResources();  
  2. rsrcs.setName(schedName);  
  3. rsrcs.setThreadName(threadName);  
  4. rsrcs.setInstanceId(schedInstId);  
  5. rsrcs.setJobRunShellFactory(jrsf);  
  6. rsrcs.setMakeSchedulerThreadDaemon(makeSchedulerThreadDaemon);  
  7. rsrcs.setThreadsInheritInitializersClassLoadContext(threadsInheritInitalizersClassLoader);  
  8. rsrcs.setRunUpdateCheck(!skipUpdateCheck);  
  9. rsrcs.setBatchTimeWindow(batchTimeWindow);  
  10. rsrcs.setMaxBatchSize(maxBatchSize);  
  11. rsrcs.setInterruptJobsOnShutdown(interruptJobsOnShutdown);  
  12. rsrcs.setInterruptJobsOnShutdownWithWait(interruptJobsOnShutdownWithWait);  
  13. rsrcs.setJMXExport(jmxExport);  
  14. rsrcs.setJMXObjectName(jmxObjectName);  
  15.   
  16. if (managementRESTServiceEnabled) {  
  17.     ManagementRESTServiceConfiguration managementRESTServiceConfiguration = new ManagementRESTServiceConfiguration();  
  18.     managementRESTServiceConfiguration.setBind(managementRESTServiceHostAndPort);  
  19.     managementRESTServiceConfiguration.setEnabled(managementRESTServiceEnabled);  
  20.     rsrcs.setManagementRESTServiceConfiguration(managementRESTServiceConfiguration);  
  21. }  
  22.   
  23. if (rmiExport) {  
  24.     rsrcs.setRMIRegistryHost(rmiHost);  
  25.     rsrcs.setRMIRegistryPort(rmiPort);  
  26.     rsrcs.setRMIServerPort(rmiServerPort);  
  27.     rsrcs.setRMICreateRegistryStrategy(rmiCreateRegistry);  
  28.     rsrcs.setRMIBindName(rmiBindName);  
  29. }  
  30.   
  31. SchedulerDetailsSetter.setDetails(tp, schedName, schedInstId);  
  32.   
  33. rsrcs.setThreadExecutor(threadExecutor);  
  34. threadExecutor.initialize();  
  35.   
  36. rsrcs.setThreadPool(tp);  
  37. if(tp instanceof SimpleThreadPool) {  
  38.     if(threadsInheritInitalizersClassLoader)  
  39.         ((SimpleThreadPool)tp).setThreadsInheritContextClassLoaderOfInitializingThread(threadsInheritInitalizersClassLoader);  
  40. }  
  41. tp.initialize();  
  42. tpInited = true;  
  43.   
  44. rsrcs.setJobStore(js);  
  45.   
  46. // add plugins  
  47. for (int i = 0; i < plugins.length; i++) {  
  48.     rsrcs.addSchedulerPlugin(plugins[i]);  
  49. }  

构造QuartzScheduler

构造QuartzScheduler的代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. qs = new QuartzScheduler(rsrcs, idleWaitTime, dbFailureRetry);  
  2. qsInited = true;  

QuartzScheduler的构造器实现见代码清单18,其处理步骤如下:
  1. 设置QuartzSchedulerResources;
  2. QuartzSchedulerResources设置的JobStore如果实现了JobListener接口,那么将其作为作业监听器添加到监听器列表;
  3. 构造线程QuartzSchedulerThread实例;
  4. 从QuartzSchedulerResources中获取设置的线程执行器;
  5. 启动QuartzSchedulerThread;
  6. 创建执行作业管理器ExecutingJobsManager,由于其实现了JobListener,所以加入了内置的作业监听器中;
  7. 创建错误日志组件ErrorLogger,由于继承了SchedulerListenerSupport,所以加入了内置的调度监听器中;
  8. 构造SchedulerSignalerImpl,此组件的作业包括:向QuartzScheduler中注册的触发器监听器发送触发器失常或者触发器再也不会被触发的信号、修改触发器下次触发的时间、向QuartzScheduler中注册的调度监听器发送作业被删除或者调度异常的信号;
  9. 当shouldRunUpdateCheck为true是则调用scheduleUpdateCheck方法(见代明清单19),实际是利用定时器定时执行UpdateChecker任务,此任务用于检查Quartz的可用的更新版本;为了提高性能,可以将属性org.quartz.scheduler.skipUpdateCheck设置为true;

代码清单18

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public QuartzScheduler(QuartzSchedulerResources resources, long idleWaitTime, @Deprecated long dbRetryInterval)  
  2.     throws SchedulerException {  
  3.     this.resources = resources;  
  4.     if (resources.getJobStore() instanceof JobListener) {  
  5.         addInternalJobListener((JobListener)resources.getJobStore());  
  6.     }  
  7.   
  8.     this.schedThread = new QuartzSchedulerThread(this, resources);  
  9.     ThreadExecutor schedThreadExecutor = resources.getThreadExecutor();  
  10.     schedThreadExecutor.execute(this.schedThread);  
  11.     if (idleWaitTime > 0) {  
  12.         this.schedThread.setIdleWaitTime(idleWaitTime);  
  13.     }  
  14.   
  15.     jobMgr = new ExecutingJobsManager();  
  16.     addInternalJobListener(jobMgr);  
  17.     errLogger = new ErrorLogger();  
  18.     addInternalSchedulerListener(errLogger);  
  19.   
  20.     signaler = new SchedulerSignalerImpl(thisthis.schedThread);  
  21.       
  22.     if(shouldRunUpdateCheck())   
  23.         updateTimer = scheduleUpdateCheck();  
  24.     else  
  25.         updateTimer = null;  
  26.       
  27.     getLog().info("Quartz Scheduler v." + getVersion() + " created.");  
  28. }  

   代码清单19

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private Timer scheduleUpdateCheck() {  
  2.     Timer rval = new Timer(true);  
  3.     rval.scheduleAtFixedRate(new UpdateChecker(), 10007 * 24 * 60 * 60 * 1000L);  
  4.     return rval;  
  5. }  

构造QuartzSchedulerThread

这里再详细分析下QuartzSchedulerThread的构造过程,其构造器见代码清单20。

代码清单20

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs) {  
  2.     this(qs, qsRsrcs, qsRsrcs.getMakeSchedulerThreadDaemon(), Thread.NORM_PRIORITY);  
  3. }  
QuartzSchedulerThread的构造器又代理了另一个构造器,见代码清单21。

代码清单21

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs, boolean setDaemon, int threadPrio) {  
  2.     super(qs.getSchedulerThreadGroup(), qsRsrcs.getThreadName());  
  3.     this.qs = qs;  
  4.     this.qsRsrcs = qsRsrcs;  
  5.     this.setDaemon(setDaemon);  
  6.     if(qsRsrcs.isThreadsInheritInitializersClassLoadContext()) {  
  7.         log.info("QuartzSchedulerThread Inheriting ContextClassLoader of thread: " + Thread.currentThread().getName());  
  8.         this.setContextClassLoader(Thread.currentThread().getContextClassLoader());  
  9.     }  
  10.   
  11.     this.setPriority(threadPrio);  
  12.   
  13.     // start the underlying thread, but put this object into the 'paused'  
  14.     // state  
  15.     // so processing doesn't start yet...  
  16.     paused = true;  
  17.     halted = new AtomicBoolean(false);  
  18. }  
代码清单21比较简单,QuartzScheduler的getSchedulerThreadGroup方法用于创建线程组,QuartzSchedulerResources的isThreadsInheritInitializersClassLoadContext方法实际获取QuartzSchedulerResources的属性threadsInheritInitializersClassLoadContext,此属性如果为真,则设置QuartzSchedulerThread的线程上下文类加载器为当前线程的类加载器,设置paused标志为true,以便于QuartzSchedulerThread线程不能开始处理。halted可以解释为叫停当前线程的执行。

阻止QuartzSchedulerThread的执行

由于在构造QuartzScheduler的过程中已经启动了QuartzSchedulerThread,那么势必导致此线程的执行,其run方法的部分代码见代码清单22.

代码清单22

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public void run() {  
  2.     boolean lastAcquireFailed = false;  
  3.   
  4.     while (!halted.get()) {  
  5.         try {  
  6.             // check if we're supposed to pause...  
  7.             synchronized (sigLock) {  
  8.                 while (paused && !halted.get()) {  
  9.                     try {  
  10.                         // wait until togglePause(false) is called...  
  11.                         sigLock.wait(1000L);  
  12.                     } catch (InterruptedException ignore) {  
  13.                     }  
  14.                 }  
  15.   
  16.                 if (halted.get()) {  
  17.                     break;  
  18.                 }  
  19.             }  
我们并未叫停调度线程的执行,所以halted属性等于false,对于paused标志而言,这里涉及多线程安全问题,所以这里使用了同步块,但是实际上可以通过调整代码将paused用volatile修饰,这样通过内存可见性省去同步,能够提高性能。由于paused标志在线程刚开始执行时为false,那么这里的white循环将不断轮询,每次循环线程wait一秒。既然QuartzSchedulerThread已经开始执行,但是却又无法执行,岂不是自相矛盾?虽然QuartzSchedulerThread线程开始启动,但是QuartzScheduler并未准备好这一切,必须等到QuartzScheduler准备时将paused修改为false。虽说这样实现也是可以的,但是在QuartzScheduler准备好的这段时间内,QuartzSchedulerThread线程频繁的睡眠、被唤醒,线程上下文来回切换,耗费了一些性能。何不等到QuartzScheduler准备好时再启动QuartzSchedulerThread线程呢?

创建调度器

创建调度器的代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // Create Scheduler ref...  
  2. Scheduler scheduler = instantiate(rsrcs, qs);  

这里创建调度器时以,实际是用StdScheduler将之前创建的QuartzScheduler进行了封装,代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. protected Scheduler instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler qs) {  
  2.   
  3.     Scheduler scheduler = new StdScheduler(qs);  
  4.     return scheduler;  
  5. }  

其他处理

剩余的工作包括:设置作业工厂,对插件初始化,给QuartzScheduler的监听器管理器注册作业监听器和触发器监听器,设置调度器上下文属性,触发JobStore,触发脚本运行工厂,将调度器注册到SchedulerRepository等,见代码清单23。

代码清单23

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // set job factory if specified  
  2. if(jobFactory != null) {  
  3.     qs.setJobFactory(jobFactory);  
  4. }  
  5.   
  6. // Initialize plugins now that we have a Scheduler instance.  
  7. for (int i = 0; i < plugins.length; i++) {  
  8.     plugins[i].initialize(pluginNames[i], scheduler, loadHelper);  
  9. }  
  10.   
  11. // add listeners  
  12. for (int i = 0; i < jobListeners.length; i++) {  
  13.     qs.getListenerManager().addJobListener(jobListeners[i], EverythingMatcher.allJobs());  
  14. }  
  15. for (int i = 0; i < triggerListeners.length; i++) {  
  16.     qs.getListenerManager().addTriggerListener(triggerListeners[i], EverythingMatcher.allTriggers());  
  17. }  
  18.   
  19. // set scheduler context data...  
  20. for(Object key: schedCtxtProps.keySet()) {  
  21.     String val = schedCtxtProps.getProperty((String) key);      
  22.     scheduler.getContext().put((String)key, val);  
  23. }  
  24.   
  25. // fire up job store, and runshell factory  
  26.   
  27. js.setInstanceId(schedInstId);  
  28. js.setInstanceName(schedName);  
  29. js.setThreadPoolSize(tp.getPoolSize());  
  30. js.initialize(loadHelper, qs.getSchedulerSignaler());  
  31.   
  32. jrsf.initialize(scheduler);  
  33.   
  34. qs.initialize();  
  35.   
  36. getLog().info(  
  37.         "Quartz scheduler '" + scheduler.getSchedulerName()  
  38.                 + "' initialized from " + propSrc);  
  39.   
  40. getLog().info("Quartz scheduler version: " + qs.getVersion());  
  41.   
  42. // prevents the repository from being garbage collected  
  43. qs.addNoGCObject(schedRep);  
  44. // prevents the db manager from being garbage collected  
  45. if (dbMgr != null) {  
  46.     qs.addNoGCObject(dbMgr);  
  47. }  
  48.   
  49. schedRep.bind(scheduler);  
  50. return scheduler;  

总结

可以看到创建调度器的过程,几乎完全是顺序编程,步骤也十分清楚。但是可以看到其中可以优化的地方也比较多,另外代码组织稍微不太合理,例如instantiate方法的长度1355-579=776行。

0 0