---
title: "定时器介绍与Spring中定时器的配置"
author: "lzstone"
date: "2010-04-27T16:33:20Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2010-04-27T16:33:20Z"
id: 654294
url: "https://lzstone.iteye.com/blog/654294"
---

**1定时器的作用**  
在实际的开发中，如果项目中需要定时执行或者需要重复执行一定的工作，定时器显现的尤为重要。  
例如，公司的考勤系统---刷卡  
      财务的审查，入账，报表都会需要定时器  
当然如果我们不了解定时器就会用线程去实现，例如：  
package org.lzstone.action  
public class FinanceAction extends Thread{  
       private Date date;  
       public void run{  
       try{  
       while(true){  
       Thread.sleep((int)(Math.random()\*1000));  
       date = new Date();  
       //定时执行任务  
       }  
       }catch(Exception e){  
        e.printStackTrace();  
       }  
}  
}  
自己实现定时器的工作很复杂，如果实现不好占用内存过多，系统就此Over，所以处理定时执行或者重复执行的任务，定时器是很好的选择  
**2.java中常见的定时器**  
1）借助Java.util.Timer来实现  
2）OpenSymphony社区提供的Quartz来实现  
**3.介绍Timer**  
利用Timer开发定时任务是主要分为两个步骤：  
1）创建定时任务类  
示例代码：  
package org.lzstone.action  
import java.util.TimeTask  
public class LzstoneTimeTask extends TimeTask{  
       public void run(){  
              //执行的定时器任务  
       }  
}  
2）运行定时任务，运行定时任务分为两种方式：  
2.1）程序直接启动  
示例代码：  
package org.lzstone.action  
public class LzstoneMain{  
       .......  
       public void run(){  
        //执行定时器的任务  
        //创建实例  
        Timer timer = new Timer();  
        参数：  
        new LzstoneTimeTask()- 所要安排的任务。  
        0- 执行任务前的延迟时间，单位是毫秒。  
        1\*1000- 执行各后续任务之间的时间间隔，单位是毫秒。  
        timer.schedule(new LzstoneTimeTask(),0,1\*1000);  
       }  
}  
2.2）web监听方式  
示例代码：  
package org.lzstone.action  
public class LzstoneMain implements ServletContextListener{  
       private Timer timer = null;  
       //初始化监听器，创建实例，执行任务  
       public void contextInitialized(ServletContextEvent event){  
               timer = new Timer();  
               timer.schedule(new LzstoneTimeTask(),0,1\*1000);  
       }  
       //销毁监听器，停止执行任务  
       public void contextDestroyed(ServletContextEvent event){  
              //注意，在此计时器调用的计时器任务的 run 方法内调用此方法，就可以绝对确保正在执行的任务是此计时器所执行的最后一个任务。  
              timer.cancel();  
        }  
}  
web.xml配置  
&lt;listener&gt;  
   &lt;listener-class&gt;  
        org.lzstone.action.LzstoneMain  
   &lt;/listener-class&gt;  
&lt;/listener&gt;  
**4. 介绍Quartz**  
Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目，可以用来创建简单或者复杂的定时任务，利用Quartz开发定时任务的步骤与Timer类

似。

利用Quartz开发定时任务是主要分为两个步骤：  
1）创建定时任务类  
示例代码：  
package org.lzstone.action  
public class LzstoneTimeTask implements Job{  
       public void execute(JobExecutionContext context) throws JobExecutionException{  
              //执行的定时器任务  
       }  
}  
2）运行定时任务，运行定时任务分为两种方式：  
2.1）程序直接启动,创建任务调度器及配置相应的任务计划  
示例代码：  
package org.lzstone.action  
public class LzstoneMain{  
       private static Scheduler sched;  
       public static void run() throws Exception{  
              //创建LzstoneTimeTask的定时任务  
              JobDetail jobDetail = new JobDetail("lzstoneJob",sched.DEFAULT\_GROUP,LzstoneTimeTask.class);  
              //目标 创建任务计划  
              CronTrigger trigger = new CronTrigger("lzstoneTrigger","lzstone","0 0 12 * * ?");  
              //0 0 12 * * ? 代表每天的中午12点触发  
              sched = new org.quartz.impl.StdSchedulerFactory().getScheduler();  
              sched.scheduleJob(jobDetail,trigger);  
              sched.start();  
       }  
       //停止  
       public static void stop() throws Exception{  
              sched.shutdown();  
        }  
}  
//执行  
public class Main{  
       .............  
       public void run(){  
            LzstoneMain.run();  
       }  
       ............  
}  
2.2）web监听方式  
示例代码：  
package org.lzstone.action  
public class LzstoneMainListener implements ServletContextListener{  
       private Timer timer = null;  
       //初始化监听器，创建实例，执行任务  
       public void contextInitialized(ServletContextEvent event){  
               LzstoneMain.run();  
       }  
       //销毁监听器，停止执行任务  
       public void contextDestroyed(ServletContextEvent event){  
              LzstoneMain.stop();  
        }  
}  
web.xml配置  
&lt;listener&gt;  
   &lt;listener-class&gt;  
        org.lzstone.action.LzstoneMainListener  
   &lt;/listener-class&gt;  
&lt;/listener&gt;  
**5.对比**  
Timer方式实现定时器，原理简单，实现方便，在执行简单的任务比较方便，不足之处是无法确定执行时间，并且依赖性比较强，必须继承指定的类  
Quartz方式实现定时器，方便，清晰指定启动时间，定时参数比较灵活，容易实现比较复杂的定时任务，不足之处是需要实现特定接口，加载其框架  
两种方式各有优缺点，在特定场合可以根据其特点选择使用。  
**6.Spring定时任务**  
Spring定时任务对Timer与Quartz都提供了支持，并且实现步骤基本一样  
**首先配置Spring对Timer的支持**  
**1.1 创建定时任务类**  
package org.lzstone.action  
import java.util.TimeTask  
public class LzstoneTimeTask extends TimeTask{  
       public void run(){  
              //执行的定时器任务  
       }  
}  
**1.2 注册定时任务类，配置任务计划与任务调度器**  
    在项目的WEB-INF下面创建TimerConfig.xml文件  
&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"&gt;  
&lt;beans&gt;  
&lt;bean&gt;  
&lt;!--注册定时执行任务实体--&gt;  
&lt;bean id="lzstoneTimeTask" class="org.lzstone.action.LzstoneTimeTask"/&gt;  
&lt;!--注册定时器信息--&gt;  
&lt;bean id="taskInfo" class="org.springframework.scheduling.timer.ScheduledTimerTask"&gt;  
&lt;!--第一次执行任务前需要等待的时间，这里设置为3秒--&gt;  
&lt;property name="delay"&gt;  
&lt;value&gt;3000&lt;/value&gt;  
&lt;/property&gt;  
&lt;!--设置任务的执行周期 这里设置为4秒--&gt;  
&lt;property name="period"&gt;  
  &lt;value&gt;4000&lt;/value&gt;  
&lt;/property&gt;  
&lt;!--设置具体执行的任务 这里设置为lzstoneTimeTask--&gt;  
&lt;property name="timerTask"&gt;  
&lt;ref local="lzstoneTimeTask"/&gt;  
&lt;/property&gt;  
&lt;/bean&gt;  
&lt;!--配置定时器任务的调度器--&gt;  
&lt;bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean"&gt;  
&lt;!--注册定时器列表--&gt;  
&lt;property name="scheduledTimerTasks"&gt;  
    &lt;list&gt;  
        &lt;ref local="taskInfo"/&gt;  
        ........  
    &lt;/list&gt;  
&lt;/property&gt;  
&lt;/bean&gt;  
&lt;/beans&gt;  
**1.3 web项目中的启动设置**  
    &lt;context-param&gt;  
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
      &lt;param-value&gt;/WEB-INF/TimerConfig.xml&lt;/param-value&gt;  
     &lt;/context-param&gt;

     &lt;listener&gt;  
         &lt;listener-class&gt;  
                  org.springframework.web.context.ContextLoaderListener  
         &lt;/listener-class&gt;  
     &lt;/listener&gt;  
**配置Spring对Quartz的支持**  
**2.1 创建定时任务类**  
package org.lzstone.action  
public class LzstoneQuartzTask{  
       public void execute(){  
              //执行的定时器任务  
       }  
}  
**2.2 注册定时任务类，配置任务计划与任务调度器**  
    在项目的WEB-INF下面创建QuartzConfig.xml文件  
&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"&gt;  
&lt;beans&gt;  
&lt;bean&gt;  
&lt;!--注册定时执行任务实体--&gt;  
&lt;bean id="lzstoneQuartzTask" class="org.lzstone.action.LzstoneQuartzTask"/&gt;  
&lt;!--注册定时器信息--&gt;  
&lt;bean id="taskInfo" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"&gt;  
&lt;!--指定要执行的定时任务类  这里是LzstoneQuartzTask--&gt;  
&lt;property name="targetObject"&gt;  
&lt;ref local="lzstoneQuartzTask"/&gt;  
&lt;/property&gt;  
&lt;!--指定定时器任务类要执行的方法名称 这里是execute--&gt;  
&lt;property name="targetMethod"&gt;  
&lt;value&gt;execute&lt;/value&gt;  
&lt;/property&gt;  
&lt;/bean&gt;  
&lt;!--配置定时器任务的调度器--&gt;  
&lt;bean id="quartzTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"&gt;  
&lt;!--声明要运行的实体--&gt;  
&lt;property name="jobDetail"&gt;  
    &lt;ref local="taskInfo"/&gt;  
&lt;/property&gt;  
&lt;!--设置运行时间--&gt;  
&lt;property name="cronExpression"&gt;  
    &lt;value&gt;0 0 12 * * ?&lt;/value&gt;  
&lt;/property&gt;  
&lt;/bean&gt;  
&lt;!--注册监听器--&gt;  
&lt;bean id="registerQuartz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"&gt;  
&lt;!--注册定时器实体 集合--&gt;  
&lt;property name="triggers"&gt;  
    &lt;list&gt;  
          &lt;ref local="quartzTrigger"/&gt;  
    &lt;/list&gt;  
&lt;/property&gt;  
&lt;/bean&gt;  
&lt;/beans&gt;  
**2.3 web项目中的启动设置**  
    &lt;context-param&gt;  
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
      &lt;param-value&gt;/WEB-INF/QuartzConfig.xml&lt;/param-value&gt;  
     &lt;/context-param&gt;

     &lt;listener&gt;  
         &lt;listener-class&gt;  
                  org.springframework.web.context.ContextLoaderListener  
         &lt;/listener-class&gt;  
     &lt;/listener&gt;  
**以上为定时器的个人总结，不足之处还希望指教**