Quartz 框架的應用

本文將簡單介紹在沒有 Spring 的時候..如何來使用 Quartz...html

 

這裏跳過 Quartz 的其餘介紹。若是想更加輸入的瞭解 Quartz,你們能夠點擊下載Quartz的幫助文檔。java

 

Quartz 和 Web 集成應用web

 

第一步: 導入quartz包..這個不用說吧..放到工程的 lib 下面便可express

 

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

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

 

       quartz.properties文件以下:spa

#----------調度器屬性-------------
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的配置:code

        從 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;  
    }  
} 
相關文章
相關標籤/搜索