`
yimeng528
  • 浏览: 183861 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Quartz之QuartzInitializerServlet

阅读更多

问题:我想在应用程序启动之后去执行任务怎么办呢! 
Quartz:使用QuartzInitializerServlet可满足需要 

参考资料 
1 Quartz调度框架应用总结 
http://java.chinaitlab.com/advance/752064_3.html 
2 Integrating quartz in a web application 
http://www.oreillynet.com/cs/user/view/cs_msg/52725 
3 基于Quartz的开源项目 
myschedule 
4 Adding multiple jobs via the quartz_jobs.xml skips jobs 
http://jira.opensymphony.com/browse/QRTZNET-250 
5 Quartz with Apache ServiceMix 
http://forums.terracotta.org/forums/posts/list/5427.page 
6 Web应用中使用Quartz进行任务调度 
http://www.hujun.me/post?id=12001 
7 Quartz的XML定义说明:New in Quartz.Net 2.0–New Job File Format 
http://jvilalta.blogspot.com/2011/03/new-in-quartznet-20new-job-file-format.html 
来自于Quartz的文档说明: 
A Servlet that can be used to initialize Quartz, if configured as a load-on-startup servlet in a web application.Using this start-up servlet may be preferred to using the QuartzInitializerListener in some situations - namely when you want to initialize more than one scheduler in the same application.You'll want to add something like this to your WEB-INF/web.xml file: 

Java代码   收藏代码
  1. <servlet>  
  2.          <servlet-name>  
  3.              QuartzInitializer  
  4.          </servlet-name>  
  5.          <display-name>  
  6.              Quartz Initializer Servlet  
  7.          </display-name>  
  8.          <servlet-class>  
  9.              org.quartz.ee.servlet.QuartzInitializerServlet  
  10.          </servlet-class>  
  11.          <load-on-startup>  
  12.              1  
  13.          </load-on-startup>  
  14.          <init-param>  
  15.              <param-name>config-file</param-name>  
  16.              <param-value>/some/path/my_quartz.properties</param-value>  
  17.          </init-param>  
  18.          <init-param>  
  19.              <param-name>shutdown-on-unload</param-name>  
  20.              <param-value>true</param-value>  
  21.          </init-param>  
  22.          <init-param>  
  23.              <param-name>wait-on-shutdown</param-name>  
  24.              <param-value>true</param-value>  
  25.          </init-param>  
  26.          <init-param>  
  27.              <param-name>start-scheduler-on-load</param-name>  
  28.              <param-value>true</param-value>  
  29.          </init-param>  
  30.      </servlet>  


相应参数说明: 

The init parameter 'config-file' can be used to specify the path (and filename) of your Quartz properties file. If you leave out this parameter, the default ("quartz.properties") will be used. 
The init parameter 'shutdown-on-unload' can be used to specify whether you want scheduler.shutdown() called when the servlet is unloaded (usually when the application server is being shutdown). Possible values are "true" or "false". The default is "true". 
The init parameter 'wait-on-shutdown' has effect when 'shutdown-on-unload' is specified "true", and indicates whether you want scheduler.shutdown(true) called when the listener is unloaded (usually when the application server is being shutdown). Passing "true" to the shutdown() call causes the scheduler to wait for existing jobs to complete. Possible values are "true" or "false". The default is "false". 

The init parameter 'start-scheduler-on-load' can be used to specify whether you want the scheduler.start() method called when the servlet is first loaded. If set to false, your application will need to call the start() method before the scheduler begins to run and process jobs. Possible values are "true" or "false". The default is "true", which means the scheduler is started. 
A StdSchedulerFactory instance is stored into the ServletContext. You can gain access to the factory from a ServletContext instance like this: 
     StdSchedulerFactory factory = (StdSchedulerFactory) ctx 
                .getAttribute(QuartzFactoryServlet.QUARTZ_FACTORY_KEY); 
The init parameter 'servlet-context-factory-key' can be used to override the name under which the StdSchedulerFactory is stored into the ServletContext, in which case you will want to use this name rather than QuartzFactoryServlet.QUARTZ_FACTORY_KEY in the above example. 
The init parameter 'scheduler-context-servlet-context-key' if set, the ServletContext will be stored in the SchedulerContext under the given key name (and will therefore be available to jobs during execution). 
The init parameter 'start-delay-seconds' can be used to specify the amount of time to wait after initializing the scheduler before scheduler.start() is called. 
Once you have the factory instance, you can retrieve the Scheduler instance by calling getScheduler() on the factory. 

所要的jar文件包含: 
quartz-all-2.0.1.jar, jta-1.1.jar,log4j-1.2.14.jar,slf4j-api-1.6.1.jar,slf4j-log4j12-1.6.1.jar 
具体代码如下: 
web.xml 

Java代码   收藏代码
  1. <servlet>  
  2.         <servlet-name>QuartzInitializer</servlet-name>  
  3.         <display-name>Quartz Initializer Servlet</display-name>  
  4.         <servlet-class>  
  5.             org.quartz.ee.servlet.QuartzInitializerServlet  
  6.         </servlet-class>  
  7.         <load-on-startup>1</load-on-startup>      
  8.           
  9.         <init-param>  
  10.             <param-name>config-file</param-name>  
  11.             <param-value>/quartz.properties</param-value>  
  12.         </init-param>  
  13.           
  14.         <init-param>  
  15.             <param-name>shutdown-on-unload</param-name>  
  16.             <param-value>true</param-value>  
  17.         </init-param>  
  18.         <!--   
  19.         <init-param>  
  20.             <param-name>start-scheduler-on-load</param-name>  
  21.             <param-value>true</param-value>  
  22.         </init-param>  
  23.         <init-param>  
  24.             <param-name>wait-on-shutdown</param-name>  
  25.             <param-value>true</param-value>  
  26.         </init-param>  
  27.          -->       
  28.     </servlet>  


位于src下:quartz.properties 

Java代码   收藏代码
  1. org.quartz.scheduler.threadsInheritContextClassLoaderOfInitializer=true  
  2. org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true  
  3. # Configure Main Scheduler Properties     
  4.  org.quartz.scheduler.instanceName=QuartzScheduler  
  5.  org.quartz.scheduler.instanceId=AUTO  
  6.  org.quartz.scheduler.skipUpdateCheck=true  
  7.  org.quartz.scheduler.threadsInheritContextClassLoaderOfInitializer=true  
  8.  # Configure ThreadPool    
  9.  org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool  
  10.  org.quartz.threadPool.threadCount=3  
  11.  org.quartz.threadPool.threadPriority=5  
  12.  org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true  
  13.  # Configure JobStore    
  14.  org.quartz.jobStore.misfireThreshold=60000   
  15.  org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore   
  16.  #org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX  
  17.  #org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate  
  18.  #org.quartz.jobStore.useProperties=false  
  19.  #org.quartz.jobStore.dataSource=myDS  
  20.  #org.quartz.jobStore.tablePrefix=QRTZ_  
  21.  #org.quartz.jobStore.isClustered=false  
  22.  # Configure Datasources    
  23.  #org.quartz.dataSource.myDS.driver=org.postgresql.Driver  
  24.  #org.quartz.dataSource.myDS.URL=jdbc:postgresql://localhost/dev  
  25.  #org.quartz.dataSource.myDS.user=jhouse  
  26.  #org.quartz.dataSource.myDS.password=  
  27.  #org.quartz.dataSource.myDS.maxConnections=5   
  28.  # Configure Plugins   
  29. org.quartz.plugin.triggHistory.class=org.quartz.plugins.history.LoggingJobHistoryPlugin  org.quartz.plugin.jobInitializer.class=org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin  
  30.  org.quartz.plugin.jobInitializer.fileNames=quartz_job.xml  
  31.  org.quartz.plugin.jobInitializer.failOnFileNotFound=true  
  32.  org.quartz.plugin.jobInitializer.scanInterval=120  
  33.  org.quartz.plugin.jobInitializer.wrapInUserTransaction=false   


有些时候其实可按需配置,如下: 

Java代码   收藏代码
  1. org.quartz.scheduler.instanceName= MyQuartzScheduler  
  2. org.quartz.scheduler.rmi.export= false  
  3. org.quartz.scheduler.rmi.proxy= false  
  4. org.quartz.scheduler.wrapJobExecutionInUserTransaction= false  
  5. org.quartz.threadPool.class= org.quartz.simpl.SimpleThreadPool  
  6. org.quartz.threadPool.threadCount= 10  
  7. org.quartz.threadPool.threadPriority= 5  
  8. org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread= true  
  9. org.quartz.jobStore.misfireThreshold= 60000  
  10. org.quartz.jobStore.class= org.quartz.simpl.RAMJobStore  
  11. org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin  
  12. #job and trigger configuration file  
  13. org.quartz.plugin.jobInitializer.fileNames =quartz_job.xml  


位于src下的:quartz_job.xml 

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <job-scheduling-data  
  3.         xmlns="http://www.quartz-scheduler.org/xml/JobSchedulingData"  
  4.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.         xsi:schemaLocation="http://www.quartz-scheduler.org/xml/JobSchedulingData   
  6.                             http://www.quartz-scheduler.org/xml/job_scheduling_data_2_0.xsd"  
  7.         version="2.0">  
  8.   
  9.         <pre-processing-commands>  
  10.                 <delete-jobs-in-group>*</delete-jobs-in-group>  <!-- clear all jobs in scheduler -->  
  11.                 <delete-triggers-in-group>*</delete-triggers-in-group> <!-- clear all triggers in scheduler -->  
  12.         </pre-processing-commands>  
  13.   
  14.         <processing-directives>  
  15.                 <!-- if there are any jobs/trigger in scheduler of same name (as in this file), overwrite them -->  
  16.                 <overwrite-existing-data>true</overwrite-existing-data>  
  17.                 <!-- if there are any jobs/trigger in scheduler of same name (as in this file), and over-write is false, ignore them rather then generating an error -->  
  18.                 <ignore-duplicates>false</ignore-duplicates>  
  19.         </processing-directives>  
  20.   
  21.         <schedule>          
  22.                 <job>  
  23.                         <name>job1</name>                       
  24.                         <job-class>net.liuzd.tools.quartz.servlet.Job1</job-class>   
  25.                 </job>  
  26.                 <trigger>  
  27.                         <cron>  
  28.                                 <name>t1</name>                                 
  29.                                 <job-name>job1</job-name>                               
  30.                                 <cron-expression>0/10 * * * * ?</cron-expression>    
  31.                         </cron>  
  32.                 </trigger>                 
  33.                   
  34.                  <job>  
  35.                         <name>job2</name>                       
  36.                         <job-class>net.liuzd.tools.quartz.servlet.Job2</job-class>   
  37.                 </job>  
  38.   
  39.                 <trigger>  
  40.                         <cron>  
  41.                                 <name>t2</name>                                 
  42.                                 <job-name>job2</job-name>                               
  43.                                 <cron-expression>0/20 * * * * ?</cron-expression>      
  44.                         </cron>  
  45.                 </trigger>                 
  46.   
  47.         </schedule>          
  48. </job-scheduling-data>  


src下的log4j.xml 

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">  
  3. <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">  
  4.   <appender name="default" class="org.apache.log4j.ConsoleAppender">  
  5.     <param name="target" value="System.out"/>  
  6.     <layout class="org.apache.log4j.PatternLayout">  
  7.       <param name="ConversionPattern" value="[%p] %d{yyyy-MM-dd hh:mm:ss.SSS aa} %t [%c]%n%m%n%n"/>  
  8.     </layout>  
  9.   </appender>  
  10.  <logger name="org.quartz">  
  11.    <level value="info" />  
  12.  </logger>  
  13.   <root>  
  14.     <level value="info" />  
  15.     <appender-ref ref="default" />  
  16.   </root>        
  17. </log4j:configuration>  


二个任务类: 

Java代码   收藏代码
  1. import java.text.SimpleDateFormat;  
  2. import java.util.Date;    
  3.     
  4. import org.quartz.Job;    
  5. import org.quartz.JobExecutionContext;    
  6. import org.quartz.JobExecutionException;    
  7. import org.slf4j.Logger;  
  8. import org.slf4j.LoggerFactory;  
  9.     
  10. public class Job1 implements Job {    
  11.       
  12.     private static Logger _log = LoggerFactory.getLogger(Job1.class);  
  13.         
  14.     public Job1() {    
  15.             
  16.     }      
  17.     
  18.     public void execute(JobExecutionContext context)    
  19.             throws JobExecutionException {    
  20.         _log.info("执行天涯的第一个任务: " + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));    
  21.     }    
  22. }    
  23.   
  24. import java.text.SimpleDateFormat;  
  25. import java.util.Date;    
  26.     
  27. import org.quartz.Job;    
  28. import org.quartz.JobExecutionContext;    
  29. import org.quartz.JobExecutionException;    
  30. import org.slf4j.Logger;  
  31. import org.slf4j.LoggerFactory;  
  32.     
  33. public class Job2 implements Job {    
  34.         
  35.     private static Logger _log = LoggerFactory.getLogger(Job2.class);  
  36.       
  37.     public Job2() {    
  38.     }    
  39.     
  40.     
  41.     public void execute(JobExecutionContext context)    
  42.             throws JobExecutionException {    
  43.         _log.info("执行天涯的第二个任务: " + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));  
  44.     }    
  45. }   


在WEB应用启动时控制台输出结果如下: 

Log代码   收藏代码
  1. [INFO] 2011-08-15 02:18:50.015 下午 QuartzScheduler_Worker-2 [org.quartz.plugins.history.LoggingJobHistoryPlugin]  
  2. Job DEFAULT.job1 fired (by trigger DEFAULT.t1) at:  14:18:50 08/15/2011  
  3.   
  4. [INFO] 2011-08-15 02:18:50.015 下午 QuartzScheduler_Worker-2 [net.liuzd.tools.quartz.servlet.Job1]  
  5. 执行天涯的第一个任务: 2011-08-15 02:18:50  
  6.   
  7. [INFO] 2011-08-15 02:18:50.015 下午 QuartzScheduler_Worker-2 [org.quartz.plugins.history.LoggingJobHistoryPlugin]  
  8. Job DEFAULT.job1 execution complete at  14:18:50 08/15/2011 and reports: null  
  9.   
  10. [INFO] 2011-08-15 02:19:00.000 下午 QuartzScheduler_Worker-3 [org.quartz.plugins.history.LoggingJobHistoryPlugin]  
  11. Job DEFAULT.job1 fired (by trigger DEFAULT.t1) at:  14:19:00 08/15/2011  
  12.   
  13. [INFO] 2011-08-15 02:19:00.000 下午 QuartzScheduler_Worker-3 [net.liuzd.tools.quartz.servlet.Job1]  
  14. 执行天涯的第一个任务: 2011-08-15 02:19:00  
  15.   
  16. [INFO] 2011-08-15 02:19:00.000 下午 QuartzScheduler_Worker-3 [org.quartz.plugins.history.LoggingJobHistoryPlugin]  
  17. Job DEFAULT.job1 execution complete at  14:19:00 08/15/2011 and reports: null  
  18.   
  19. [INFO] 2011-08-15 02:19:00.000 下午 QuartzScheduler_Worker-1 [org.quartz.plugins.history.LoggingJobHistoryPlugin]  
  20. Job DEFAULT.job2 fired (by trigger DEFAULT.t2) at:  14:19:00 08/15/2011  
  21.   
  22. [INFO] 2011-08-15 02:19:00.000 下午 QuartzScheduler_Worker-1 [net.liuzd.tools.quartz.servlet.Job2]  
  23. 执行天涯的第二个任务: 2011-08-15 02:19:00  
分享到:
评论

相关推荐

    quartz-2.3.2-API文档-中文版.zip

    赠送jar包:quartz-2.3.2.jar; 赠送原API文档:quartz-2.3.2-javadoc.jar; 赠送源代码:quartz-2.3.2-sources.jar; 赠送Maven依赖信息文件:quartz-2.3.2.pom; 包含翻译后的API文档:quartz-2.3.2-javadoc-API...

    quartz指南,Quartz 工程

    文件里面包括 1:Quartz开发指南.pdf 2:Quartz从入门到进阶.pdf 3:QuartzBeginnerExample一个附带的工程例子 4:quartz-1.6.1.zip Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它...

    quartz-1.6.0.jar和quartz-all-1.6.0.jar

    该压缩包内包含两个quartz的jar包, 分别是quartz-1.6.0.jar和quartz-all-1.6.0.jar

    quartz-2.3.0-API文档-中文版.zip

    赠送jar包:quartz-2.3.0.jar; 赠送原API文档:quartz-2.3.0-javadoc.jar; 赠送源代码:quartz-2.3.0-sources.jar; 赠送Maven依赖信息文件:quartz-2.3.0.pom; 包含翻译后的API文档:quartz-2.3.0-javadoc-API...

    quartz-2.2.3版本的quartz初始化sql语句

    quartz-2.2.3版本的quartz初始化sql语句

    quartz简单实例quartz简单实例

    quartz简单实例quartz简单实例quartz简单实例quartz简单实例

    Autofac.Extras.Quartz, Quartz.Net的Autofac集成.zip

    Autofac.Extras.Quartz, Quartz.Net的Autofac集成 Autofac.Extras.Quartz用于 Quartz.Net的Autofac集成包。Autofac.Extras.Quartz 为每个石英作业创建嵌套的litefime作用域。 完成作业执行后释放嵌套作用域。这允许...

    自开发实现Quartz Web管理工具

    网上能找到的Quartz Web管理的资料都是使用的一个国外人写的Quartz WebApp的东东,功能也很全面。但是作为自己的应用其实用不了那么多功能,一般我们只要可以定义一个job,指定一个Cron表达式完成工作即可,附带的...

    quartz quartz-1.8.6 dbTables 建表sql

    quartz quartz-1.8.6 dbTables quartz动态任务调度需要的数据库脚本。

    quartz内部表.sql

    quartz内部表.sql。

    quartz1.5,quartz1.6,quartz1.8

    Quartz1.5,Quartz1.6,Quartz1.8。Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个,百个,甚至是好几万个...

    postgres-quartz.sql

    postgres quatrz初始化sql脚本文件、pg、quartz、qrtz_开头的表 配置文件需求修改 #org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate org.quartz.jobStore....

    Quartz.NET-2.0

    Quartz.NET框架的核心是调度器。调度器负责管理Quartz.NET应用运行时环境。Quartz不仅仅是线程和线程管理。为确保可伸缩性,Quartz.NET采用了基于多线程的架构。启动时,框架初始化一套worker线程,这套线程被调度器...

    Quartz原理及实例

    Quartz原理及实例,spring4.x+Quartz.2.2.1结合的开发,静态和动态实例

    lucene与quartz例子

    lucene quartz 例子lucene quartz 例子lucene quartz 例子lucene quartz 例子lucene quartz 例子lucene quartz 例子lucene quartz 例子lucene quartz 例子lucene quartz 例子lucene quartz 例子

    关于spring中quartz的配置

    关于spring中quartz的配置

    深入解读Quartz的原理

    深入解读Quartz的原理,定时任务框架是web开发过程中使用很多的框架之一

    Quartz-2.0.2 CSDN下载

    Quartz框架的核心是调度器。调度器负责管理Quartz应用运行时环境。调度器不是靠自己做所有的工作,而是依赖框架内一些非常重要的部件。 Quartz不仅仅是线程和线程管理。为确保可伸缩性,Quartz采用了基于多线程的...

    Quartz之CronExpression详解

    详细介绍CronExpression表达式设定定时任务的规则

    quartz3种调度形式+传参.zip

    quartz自动调度的3种调度形式+传参 1.单纯的quartz调度 2.spring+quartz调度

Global site tag (gtag.js) - Google Analytics