当前位置: 首页 > news >正文

Quartz 框架的应用

本文将简单介绍在没有 Spring 的时候..如何来使用 Quartz...

 

这里跳过 Quartz 的其他介绍。如果想更加输入的了解 Quartz,大家可以点击下载Quartz的帮助文档。

 

Quartz 和 Web 集成应用

 

第一步: 导入quartz包..这个不用说吧..放到工程的 lib 下面即可

 

第二步: 添加相应文件和修改web.xml文件的配置.

        添加 quartz.properties 和 quartz_jobs.xml 到 src 下面

 

       quartz.properties文件如下:

#----------调度器属性-------------
org.quartz.scheduler.instanceName = QuartzScheduler       
org.quartz.scheduler.instanceId = AUTO

#------------线程配置------------------
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5
org.quartz.threadPool.threadPriority = 5

#---------------作业存储设置---------------
org.quartz.jobStore.class=org.quzrtz.simpl.RAMJobStore

#---------------插件配置----------------

org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin        
org.quartz.plugins.xml.JobInitializationPlugin = quartz_jobs.xml     
      
org.quartz.plugin.jobInitializer.overWriteExistingJobs = false        
org.quartz.plugin.jobInitializer.validating = false        
org.quartz.plugin.jobInitializer.failOnFileNotFound =true  

quartz_jobs.xml 文件如下

<?xml version="1.0" encoding="UTF-8"?>  
<quartz>  
    <job>  
  
        <job-detail>  
            <name>GatherJob</name>  
            <group>DEFAULT</group>  
            <description>GatherJob</description>  
            <job-class>net.sf.rain.gather.quartz.GatherJob</job-class>  
            <volatility>false</volatility>  
            <durability>false</durability>  
            <recover>false</recover>  
        </job-detail>  
  
        <trigger>  
            <cron>  
                <name>RunQuartzJobTrigger</name>  
                <group>DEFAULT</group>  
                <description>RunQuartzJobTrigger</description>  
                <job-name>RunQuartzJob</job-name>  
                <job-group>DEFAULT</job-group>  
                <!--  <cron-expression>0/60 * * * * ?</cron-expression> -->  
                <cron-expression>0 0 3 * * ?</cron-expression>  
            </cron>  
        </trigger>  
  
    </job>  
</quartz>  

注意文件中的配置要正确。比如 job-class 等等。

web.xml的配置:

        从 2.3 版本的 Servlet API 开始,你能创建监听器,由容器在其生命周期中的某个特定时间回调。其中的一个监听器接口叫做 java.servlet.ServletContextListener,

WEB.xml

<!-- ====================== Quartz config start ====================== -->  
<context-param>  
    <param-name>config-file</param-name>  
    <param-value>/quartz.properties</param-value>  
</context-param>  
  
<context-param>  
    <param-name>shutdown-on-unload</param-name>  
    <param-value>true</param-value>  
</context-param>  
  
<context-param>  
    <param-name>start-scheduler-on-load</param-name>  
    <param-value>true</param-value>  
</context-param>  
<!-- 默认情况下配置 Quzrtz 自带的监听器..但是真正项目开发中。我们是否开启定时任务应该是人工配置,所以我们需要自定义监听器 -->  
<!--   
<listener>  
        <listener-class>org.quartz.ee.servlet.QuartzInitializerListener</listener-class>  
   </listener>  
-->  
<listener>    
   <listener-class>    
        net.sf.rain.gather.quartz.QuartzServletContextListener     
   </listener-class>    
</listener>   
   
<!-- ====================== Quartz config end ====================== -->  

    下面我们将实现这个监听器   QuartzServletContextListener

package net.sf.rain.gather.quartz;  
  
import javax.servlet.ServletContext;  
import javax.servlet.ServletContextEvent;  
import javax.servlet.ServletContextListener;  
  
import org.apache.commons.logging.Log;  
import org.apache.commons.logging.LogFactory;  
import org.quartz.SchedulerException;  
import org.quartz.impl.StdSchedulerFactory;  
  
public class QuartzServletContextListener implements ServletContextListener {  
  
    private static  Log _log = LogFactory.getLog(QuartzServletContextListener.class);  
  
    public static final String QUARTZ_FACTORY_KEY = "org.quartz.impl.StdSchedulerFactory.KEY";  
    private ServletContext ctx = null;  
    private StdSchedulerFactory factory = null;  
  
    /** 
     * Called when the container is shutting down.  
     */  
    public void contextDestroyed(ServletContextEvent sce) {  
        try {  
            factory.getDefaultScheduler().shutdown();  
        } catch (SchedulerException ex) {  
            _log.error("Error stopping Quartz", ex);  
        }  
    }  
  
      
    /** 
     * 容器的第一次启动时调用 
     */  
    public void contextInitialized(ServletContextEvent sce) {  
        ctx = sce.getServletContext();  
        try {  
            factory = new StdSchedulerFactory();  
            // Start the scheduler now  
            //设置容器启动时不立即启动定时器,而是到后台人工启动  
            //factory.getScheduler().start();  
            _log.info("Storing QuartzScheduler Factory at" + QUARTZ_FACTORY_KEY);  
            ctx.setAttribute(QUARTZ_FACTORY_KEY, factory);  
  
        } catch (Exception ex) {  
            _log.error("Quartz failed to initialize", ex);  
        }  
    }  
  
}  

下面的Action将管理定时器的状态

package net.sf.rain.gather.quartz;  
  
import java.io.PrintWriter;  
  
import javax.servlet.ServletContext;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.apache.commons.lang.StringUtils;  
import org.apache.commons.logging.Log;  
import org.apache.commons.logging.LogFactory;  
import org.apache.struts.action.Action;  
import org.apache.struts.action.ActionForm;  
import org.apache.struts.action.ActionForward;  
import org.apache.struts.action.ActionMapping;  
import org.quartz.Scheduler;  
import org.quartz.SchedulerException;  
import org.quartz.impl.StdSchedulerFactory;  
  
/** 
 *  
 * 调度器管理  
 *  
 * @author 
 * 
 */  
public class GatherJobAction extends  Action{  
  
    private static  Log _log = LogFactory.getLog(GatherJobAction.class);  
      
    public ActionForward execute(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response)  
            throws Exception {  
          
        request.setCharacterEncoding("UTF-8");  
        response.setContentType("text/html;charset=UTF-8");  
          
        String action = request.getParameter("action");  
            
          
        String retMsg = "Parameter Error: action is null";  
        if (StringUtils.isNotBlank(action)) {  
            ServletContext ctx =  request.getSession().getServletContext();  
            // Retrieve the factory from the ServletContext     
            StdSchedulerFactory factory =  (StdSchedulerFactory)ctx.getAttribute(QuartzServletContextListener.QUARTZ_FACTORY_KEY);     
            // Retrieve the scheduler from the factory     
            Scheduler scheduler = factory.getScheduler();   
              
            if ("start".equals(action)) {  
                // Start the scheduler   
                try {  
                     if (!scheduler.isStarted()) {  
                         scheduler.start();  
                     }  
                     retMsg = "Quartz Successful to startup";  
                 } catch (SchedulerException ex) {  
                     _log.error("Error starting Quartz", ex);  
                     retMsg = "Quartz failed to startup";  
                 }  
            }else if("stop".equals(action)){  
                try {  
                    if (scheduler.isStarted()) {  
                        scheduler.shutdown();  
                    }  
                    retMsg = "Quartz Successful to stopping";  
                 } catch (SchedulerException ex) {  
                    _log.error("Error stopping Quartz", ex);  
                    retMsg = "Quartz failed to stopping";  
                 }  
            }else { //查看调度器的状态  
                if (scheduler.isStarted()) {  
                    retMsg = "Quartz is Started";  
                }else {  
                    retMsg = "Quartz is Stoped";  
                }  
            }  
        }  
        PrintWriter out = response.getWriter();  
        out.print(retMsg);  
        out.flush();  
        out.close();  
        return null;  
    }  
} 

 

相关文章:

  • 直接启动tomcat时为tomcat指定JDK 而不是读取环境变量中的配置
  • php 路径
  • 服务器之间,相同帐号,实现免密钥登录
  • 【noi 2.6_9289】Ant Counting 数蚂蚁{Usaco2005 Nov}(DP)
  • 数据获取以及处理系统 --- 功能规格说明书
  • 【JAVA】设计模式之懒汉式与恶汉式的单例模式实现的方法与详解
  • asp.net定时任务
  • 14. Html5的局:WebGL的纹理格式
  • Tomcat编译jsp生成Servlet文件的存放位置
  • Android事件总线(三)otto用法全解析
  • 反思总结然后整装待发
  • 当SetTimeout遇到了字符串
  • ABP文档 - EntityFramework 集成
  • [Java基础] Java中List.remove报错UnsupportedOperationException
  • 查看linux服务器的系统信息
  • Android Volley源码解析
  • IDEA常用插件整理
  • iOS高仿微信项目、阴影圆角渐变色效果、卡片动画、波浪动画、路由框架等源码...
  • Java 11 发布计划来了,已确定 3个 新特性!!
  • JAVA之继承和多态
  • mac修复ab及siege安装
  • node-glob通配符
  • SwizzleMethod 黑魔法
  • Webpack4 学习笔记 - 01:webpack的安装和简单配置
  • yii2中session跨域名的问题
  • 测试如何在敏捷团队中工作?
  • 大主子表关联的性能优化方法
  • 服务器从安装到部署全过程(二)
  • 机器学习 vs. 深度学习
  • 猫头鹰的深夜翻译:Java 2D Graphics, 简单的仿射变换
  • 排序(1):冒泡排序
  • 如何合理的规划jvm性能调优
  • 双管齐下,VMware的容器新战略
  • ​Z时代时尚SUV新宠:起亚赛图斯值不值得年轻人买?
  • #【QT 5 调试软件后,发布相关:软件生成exe文件 + 文件打包】
  • #HarmonyOS:基础语法
  • #QT(TCP网络编程-服务端)
  • #我与Java虚拟机的故事#连载07:我放弃了对JVM的进一步学习
  • (10)STL算法之搜索(二) 二分查找
  • (2)(2.4) TerraRanger Tower/Tower EVO(360度)
  • (C语言)输入自定义个数的整数,打印出最大值和最小值
  • (libusb) usb口自动刷新
  • (windows2012共享文件夹和防火墙设置
  • (第9篇)大数据的的超级应用——数据挖掘-推荐系统
  • (附源码)计算机毕业设计ssm本地美食推荐平台
  • (篇九)MySQL常用内置函数
  • (一) springboot详细介绍
  • (一)基于IDEA的JAVA基础1
  • (转) Android中ViewStub组件使用
  • ./configure,make,make install的作用
  • .360、.halo勒索病毒的最新威胁:如何恢复您的数据?
  • .NET CLR Hosting 简介
  • .net core webapi Startup 注入ConfigurePrimaryHttpMessageHandler
  • .Net Framework 4.x 程序到底运行在哪个 CLR 版本之上
  • .net 后台导出excel ,word