本文将简单介绍在没有 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; } }