---
title: "由删除聊天记录想到的技术支持方案之quartz浅析"
author: "changkunyang"
date: "2009-03-20T11:00:37Z"
tags: []
slug: "quartz"
draft: false
lastmod: "2009-03-20T11:00:37Z"
id: 352043
url: "https://changkunyang.iteye.com/blog/352043"
---

今天想调一下前几天的51聊天消息看看，郁闷的是居然发现上个月（今天9月4号）的消息被删除掉了。51的解释是“系统每隔一个月清空一次短消息记录”。可能是程序员的通病，遇上比较有意思的事第一反应就是怎么实现的？
    当然我是不知道51是怎么实现的，但是我知道如果我来做的话，我会怎么实现。以前也有遇上过定期维护数据库的问题，比如删除临时表的记录，比如删除用户登陆的记录。通常都是在后台启动一个线程，让它去执行，但是单独的java的线程很让人郁闷，于是上网搜到一个叫Quartz的开源工具，其官方解释“Quartz 是个开放源码项目，提供了丰富的作业调度集。”（具体介绍可参考http://www.ibm.com/developerworks/cn/java/j-quartz/）。
    那么在WEB的APPLICATION中怎么应用Quartz？follow me!
    一、下载相应的包。
    下载 Quartz API。 
    解压缩并把 quartz-x.x.x.jar 放在项目文件夹内，或者把文件放在项目的类路径中。 
    把 core 和/或 optional 文件夹中的 jar 文件放在项目的文件夹或项目的类路径中。 
    如果使用 JDBCJobStore，把所有的 JDBC jar 文件放在项目的文件夹或项目的类路径中。
    二、开始编写你的HELLO WORLD
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
     public class Helloworld implements Job{
       public Helloworld() {

       }

       public void execute(JobExecutionContext context)
         throws JobExecutionException {
           System.out.println("Hello World!");
            //真正在项目的应用中，这里你可以做任何你想做的操作。
            }
        }
   三、调用线程。
    怎么调呢？你只要知道三个相关的配置文件就可以。
    1。quartz.properties （注意，这个文件的名字默认），其内容如下
        #=============================================================
        # Configure Main Scheduler Properties  
        #=============================================================
        org.quartz.scheduler.instanceName =org.quartz.scheduler.instanceId = AUTO
        #=============================================================
        # Configure ThreadPool  
        #=============================================================
        org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
        org.quartz.threadPool.threadCount = 3
        org.quartz.threadPool.threadPriority = 5
        #=============================================================
        # Configure Plugins 
        #=============================================================
        org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin
        org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
        org.quartz.plugin.jobInitializer.fileName = /quartz_jobs.xml
        org.quartz.plugin.jobInitializer.overWriteExistingJobs = true
        org.quartz.plugin.jobInitializer.failOnFileNotFound = true
        org.quartz.plugin.jobInitializer.scanInterval = 10
                
                
    注意到org.quartz.plugin.jobInitializer.fileName = /quartz_jobs.xml了吗？对！接下来就是quartz_jobs.xml，配置如下：
        <?xml version="1.0" encoding="GBK"?>
        <quartz>
        <job>
          <job-detail>
            <name>Helloworld</name>
            <group>DEFAULT</group>
            <job-class>com.yck.timer.Helloworld</job-class>
          </job-detail>
          <trigger>
            <cron>
                <name>hw</name>
                <group>DEFAULT</group>
                <job-name>Helloworld</job-name>
                <job-group>DEFAULT</job-group>
                <cron-expression>0 30 0 * * ?</cron-expression>
            </cron>
          </trigger>
            </job>
        </quartz>
                
                
   可以看到，在配置文件中把jobdetail和trigger都作了完整的定义，并组合成一个job。
    注意这一行：<cron-expression>0 30 0 * * ?</cron-expression>，它定义了什么时候调度Job.关于格式，我将在后面说明。
    下面，我们把上面两个文件都放入/WEB-INF/classes目录下，然后按照api中的说明修改一下web.xml。
    <servlet>
        <servlet-name>
            QuartzInitializer
        </servlet-name>
        <display-name>
            Quartz Initializer Servlet
        </display-name>
        <servlet-class>
            org.quartz.ee.servlet.QuartzInitializerServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>config-file</param-name>
            <param-value>/quartz.properties</param-value>
        </init-param>
        <init-param>
            <param-name>shutdown-on-unload</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>
    
    启动服务看看，是不是在在控制台看见了“hello world!”？
    
    补充：Cron-Expression配置说明

字段    允许值            允许的特殊字符
秒      0-59              , - * /
分      0-59              , - * /
小时    0-23              , - * /
日期    1-31              , - * ? / L W C
月份  1-12 或者 JAN-DEC  , - * /
星期  1-7 或者 SUN-SAT    , - * ? / L C #
年（可选）留空, 1970-2099  , - * /

Cron 配置说明
表示方式
意义 

"0 0 12 * * ?" 
Fire at 12pm (noon) every day 

"0 15 10 ? * *" 
Fire at 10:15am every day 

"0 15 10 * * ?" 
Fire at 10:15am every day 

"0 15 10 * * ? *" 
Fire at 10:15am every day 

"0 15 10 * * ? 2005" 
Fire at 10:15am every day during the year 2005 

"0 * 14 * * ?" 
Fire every minute starting at 2pm and ending at 2:59pm, every day 

"0 0/5 14 * * ?" 
Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day 

"0 0/5 14,18 * * ?" 
Fire every 5 minutes starting at 2pm and ending at 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every day 

"0 0-5 14 * * ?" 
Fire every minute starting at 2pm and ending at 2:05pm, every day 

"0 10,44 14 ? 3 WED" 
Fire at 2:10pm and at 2:44pm every Wednesday in the month of March. 

"0 15 10 ? * MON-FRI" 
Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday 

"0 15 10 15 * ?" 
Fire at 10:15am on the 15th day of every month 

"0 15 10 L * ?" 
Fire at 10:15am on the last day of every month 

"0 15 10 ? * 6L" 
Fire at 10:15am on the last Friday of every month 

"0 15 10 ? * 6L" 
Fire at 10:15am on the last Friday of every month 

"0 15 10 ? * 6L 2002-2005" 
Fire at 10:15am on every last friday of every month during the years 2002, 2003, 2004 and 2005 

"0 15 10 ? * 6#3" 
Fire at 10:15am on the third Friday of every month