`
feicer
  • 浏览: 133194 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Quartz 的Web 应用-监听器方式调用

阅读更多
A ServletContextListner that can be used to initialize Quartz.

配置和集成 Quartz 到 Web 应用的一种方式。从 2.3 版本的 Servlet API 开始,能创建监听器,由容器在其生命周期中的某个特定时间回调。其中的一个监听器接口叫做 java.servlet.ServletContextListener,它包括有两个方法:

public void contextInitialized(ServletContextEvent sce);
public void contextDestroyed(ServeltContextEvent sce);


容器会在启动和关闭的时候相应的调用这两个方法。这就可以在 contextInitialized() 方法中初始化 Quartz Scheduler,并通过 contextDestroyed() 方法关闭它。
下面是QuartzInitializerListener 源码:
/**//*
 * Copyright 2004-2005 OpenSymphony
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 */

/**//*
 * Previously Copyright (c) 2001-2004 James House
 */
package org.quartz.ee.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;

/** *//**
 * <p>
 * A ServletContextListner that can be used to initialize Quartz.
 * </p>
 *
 * <p>
 * You'll want to add something like this to your WEB-INF/web.xml file:
 *
 * <pre>
 *     &lt;context-param&gt;
 *         &lt;param-name&gt;config-file&lt;/param-name&gt;
 *         &lt;param-value&gt;/some/path/my_quartz.properties&lt;/param-value&gt;
 *     &lt;/context-param&gt;
 *     &lt;context-param&gt;
 *         &lt;param-name&gt;shutdown-on-unload&lt;/param-name&gt;
 *         &lt;param-value&gt;true&lt;/param-value&gt;
 *     &lt;/context-param&gt;
 *     &lt;context-param&gt;
 *         &lt;param-name&gt;start-scheduler-on-load&lt;/param-name&gt;
 *         &lt;param-value&gt;true&lt;/param-value&gt;
 *     &lt;/context-param&gt;
 *     
 *     &lt;listener&gt;
 *         &lt;listener-class&gt;
 *             org.quartz.ee.servlet.QuartzInitializerListener
 *         &lt;/listener-class&gt;
 *     &lt;/listener&gt;
 * </pre>
 *
 * </p>
 * <p>
 * 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.
 * </p>
 *
 * <p>
 * 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".
 * </p>
 *
 * <p>
 * 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.
 * </p>
 *
 * A StdSchedulerFactory instance is stored into the ServletContext. You can gain access
 * to the factory from a ServletContext instance like this:
 * <br>
 * <pre>
 * StdSchedulerFactory factory = (StdSchedulerFactory) ctx
 *                .getAttribute(QuartzInitializerListener.QUARTZ_FACTORY_KEY);</pre>
 * <p>
 * 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 
 * <code>QuartzInitializerListener.QUARTZ_FACTORY_KEY</code> in the above example.
 * </p>
 *
 * <p>
 * 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.
 * </p>
 *
 * Once you have the factory instance, you can retrieve the Scheduler instance by calling
 * <code>getScheduler()</code> on the factory.
 *
 * @author James House
 * @author Chuck Cavaness
 * @author John Petrocik
 */
public class QuartzInitializerListener implements ServletContextListener {

    public static final String QUARTZ_FACTORY_KEY = "org.quartz.impl.StdSchedulerFactory.KEY";

    private boolean performShutdown = true;

    private Scheduler scheduler = null;

    /**//*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Interface.
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    public void contextInitialized(ServletContextEvent sce) {

        System.out.println("Quartz Initializer Servlet loaded, initializing Scheduler");

        ServletContext servletContext = sce.getServletContext();
        StdSchedulerFactory factory;
        try {

            String configFile = servletContext.getInitParameter("config-file");
            String shutdownPref = servletContext.getInitParameter("shutdown-on-unload");

            if (shutdownPref != null) {
                performShutdown = Boolean.valueOf(shutdownPref).booleanValue();
            }

            // get Properties
            if (configFile != null) {
                factory = new StdSchedulerFactory(configFile);
            } else {
                factory = new StdSchedulerFactory();
            }

            // Always want to get the scheduler, even if it isn't starting, 
            // to make sure it is both initialized and registered.
            scheduler = factory.getScheduler();

            // Should the Scheduler being started now or later
            String startOnLoad = servletContext
                    .getInitParameter("start-scheduler-on-load");

            int startDelay = 0;
            String startDelayS = servletContext.getInitParameter("start-delay-seconds");
            try {
                if(startDelayS != null && startDelayS.trim().length() > 0)
                    startDelay = Integer.parseInt(startDelayS);
            } catch(Exception e) {
                System.out.println("Cannot parse value of 'start-delay-seconds' to an integer: " + startDelayS + ", defaulting to 5 seconds.");
                startDelay = 5;
            }

            /**//*
             * If the "start-scheduler-on-load" init-parameter is not specified,
             * the scheduler will be started. This is to maintain backwards
             * compatability.
             */
            if (startOnLoad == null || (Boolean.valueOf(startOnLoad).booleanValue())) {
                if(startDelay <= 0) {
                    // Start now
                    scheduler.start();
                    System.out.println("Scheduler has been started");
                }
                else {
                    // Start delayed
                    scheduler.startDelayed(startDelay);
                    System.out.println("Scheduler will start in " + startDelay + " seconds.");
                }
            } else {
                System.out.println("Scheduler has not been started. Use scheduler.start()");
            }

            String factoryKey = 
                servletContext.getInitParameter("servlet-context-factory-key");
            if (factoryKey == null) {
                factoryKey = QUARTZ_FACTORY_KEY;
            }

            System.out.println("Storing the Quartz Scheduler Factory in the servlet context at key: "
                    + factoryKey);
            servletContext.setAttribute(factoryKey, factory);

        } catch (Exception e) {
            System.out.println("Quartz Scheduler failed to initialize: " + e.toString());
            e.printStackTrace();
        }
    }

    public void contextDestroyed(ServletContextEvent sce) {

        if (!performShutdown) {
            return;
        }

        try {
            if (scheduler != null) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            System.out.println("Quartz Scheduler failed to shutdown cleanly: " + e.toString());
            e.printStackTrace();
        }

        System.out.println("Quartz Scheduler successful shutdown.");
    }


}
分享到:
评论

相关推荐

    Quartz-Job-Scheduling-Framework-中文版-V0.9.1.zip

    内容提要:调用监听方法的线程,按什么顺序调用监听方法,最后列了一些能够把监听器应用到什么地方。 第八章. 使用 Quartz 插件 (第一部分) 内容提要:开始介绍 Quartz 插件,以及它要实现的接口和其中的三个接口...

    Spring3.x企业应用开发实战(完整版) part1

    12.2.4 添加Hibernate事件监听器 12.2.5 使用原生Hibernate API 12.2.6 使用注解配置 12.2.7 事务处理 12.2.8 延迟加载的问题 12.3 在Spring中使用myBatis 12.3.1 配置SqlMapClient 12.3.2 在Spring配置myBatis ...

    Spring.3.x企业应用开发实战(完整版).part2

    12.2.4 添加Hibernate事件监听器 12.2.5 使用原生Hibernate API 12.2.6 使用注解配置 12.2.7 事务处理 12.2.8 延迟加载的问题 12.3 在Spring中使用myBatis 12.3.1 配置SqlMapClient 12.3.2 在Spring配置myBatis ...

    spring in action英文版

     7.3.2 使用Quartz调度器  7.3.3 按调度计划调用方法  7.4 使用JMS发送消息  7.4.1 使用JMS模板发送消息  7.4.2 消费消息  7.4.3 转换消息  7.5 小结 第三部分 Spring在Web层的应用  第8章...

    Spring in Action(第二版 中文高清版).part2

    10.3.1 创建消息监听器 10.3.2 编写纯POJO MDP 10.4 使用基于消息的RPC 10.4.1 引入Lingo 10.4.2 输出服务 10.4.3 代理JMS 10.5 小结 第11章 Spring和EJB 11.1 在Spring中置入EJB 11.1.1 代理会话Bean...

    Spring in Action(第二版 中文高清版).part1

    10.3.1 创建消息监听器 10.3.2 编写纯POJO MDP 10.4 使用基于消息的RPC 10.4.1 引入Lingo 10.4.2 输出服务 10.4.3 代理JMS 10.5 小结 第11章 Spring和EJB 11.1 在Spring中置入EJB 11.1.1 代理会话Bean...

    Spring in Action(第2版)中文版

    10.3.1创建消息监听器 10.3.2编写纯pojomdp 10.4使用基于消息的rpc 10.4.1引入lingo 10.4.2输出服务 10.4.3代理jms 10.5小结 第11章spring和ejb 11.1在spring中置入ejb 11.1.1代理会话bean(ejb2.x) 11.1.2...

    JBOSS ESB程序员指南

    6.19. 监听器、信使和动作 39 6.20. 响应处理 43 6.21. 执行过程中的错误处理 43 6.22. 元数据和过滤器 44 6.23. 什么是服务 45 6.24. 服务调用者 45 7. 第五章 使用消息 47 7.1. 怎样使用消息 47 7.2. 消息的结构 ...

    Spring-Reference_zh_CN(Spring中文参考手册)

    3.8.4. ApplicationContext在WEB应用中的实例化 3.9. 粘合代码和可怕的singleton 3.9.1. 使用Singleton-helper类 4. 资源 4.1. 简介 4.2. Resource 接口 4.3. 内置 Resource 实现 4.3.1. UrlResource 4.3.2. Class...

    Spring中文帮助文档

    3.8.5. ApplicationContext在WEB应用中的实例化 3.9. 粘合代码和可怕的singleton 3.10. 以J2EE RAR文件的形式部署Spring ApplicationContext 3.11. 基于注解(Annotation-based)的配置 3.11.1. @Autowired ...

    Spring API

    3.8.5. ApplicationContext在WEB应用中的实例化 3.9. 粘合代码和可怕的singleton 3.10. 以J2EE RAR文件的形式部署Spring ApplicationContext 3.11. 基于注解(Annotation-based)的配置 3.11.1. @Autowired ...

    spring chm文档

    3.8.4. ApplicationContext在WEB应用中的实例化 3.9. 粘合代码和可怕的singleton 3.9.1. 使用Singleton-helper类 4. 资源 4.1. 简介 4.2. Resource 接口 4.3. 内置 Resource 实现 4.3.1. UrlResource 4.3.2. ...

    Spring 2.0 开发参考手册

    3.8.4. ApplicationContext在WEB应用中的实例化 3.9. 粘合代码和可怕的singleton 3.9.1. 使用Singleton-helper类 4. 资源 4.1. 简介 4.2. Resource 接口 4.3. 内置 Resource 实现 4.3.1. UrlResource 4.3.2. ...

    Spring攻略(第二版 中文高清版).part2

    11.6 为一个应用的领域类生成CRUD控制器和视图 454 11.6.1 问题 454 11.6.2 解决方案 454 11.6.3 工作原理 455 11.7 国际化(I18n)信息属性 458 11.7.1 问题 458 11.7.2 解决方案 458 11.7.3 工作原理...

    Spring攻略(第二版 中文高清版).part1

    11.6 为一个应用的领域类生成CRUD控制器和视图 454 11.6.1 问题 454 11.6.2 解决方案 454 11.6.3 工作原理 455 11.7 国际化(I18n)信息属性 458 11.7.1 问题 458 11.7.2 解决方案 458 11.7.3 工作原理...

    matlab最简单的代码-TimeSystem:定时执行系统

    用来作为各种程序的中间层,为了解决被调用程序的日志,耗时等功能而存在的。使用执行器模式以后, 相较于原来。执行各种程序更加灵活,可配置。获取程序状态和日志更加方便 helpRunTest 执行器的测试 TimeSystem ...

Global site tag (gtag.js) - Google Analytics