`

Timer和spring的Quartz两种定时器的区别。

阅读更多

第一个例子。timer定时器。(这个比较简单,timer是java.util包下一个类)
为了更好的了解,我写了两个定时器类,很被集成TimerTask。

public class MyTask extends TimerTask{
            int count = 0; 
 public void run() {
          System.out.println("定时器TimerTask启动"+count);
         count++;
       }

}
++++++++++++++++++++++++++++++++++++++++++++

public class MyTaskB extends TimerTask{
           int count = 0; 
 public void run() {
         System.out.println("定时器MyTaskB启动"+count);
        count++;
     }
}
+++++++++++++++++++++++++++++++++++++++++++

在main方法中测试
 Timer timer=new Timer();
 /**
     * 定时器任务制定,执行
     * @param tag: 0.在指定的时间里,执行指定的任务;
     *             1.在指定的时间里,按照指定的延迟,重复执行指定任务;
     *             2.从指定的延迟后,执行指定任务;
     *             3.从指定的延迟后,按照指定的延迟,重复执行指定的任务。
     *             
     * @param mydate:指定的执行时间。只有在tag等于0、1才需要指定。            
     * @param delay: 延迟执行时间,毫秒数。只有在tag等于1、3才需要指定。
     * @param period:间隔执行时间,毫秒数。只有在tag等于4才需要指定。
     */ 
     
    //定时器,执行任务测试 
    public static void main(String[] args) {   
     new TestA().timer.schedule(new MyTask(), 1000);
        new TestA().timer.schedule(new MyTaskB(), 4000);
    } 

注:timer还可以在web中应用。直接把MyTask()和MyTaskB()里面的方法作修改即可,也可以在任务完成后关掉timer定时。
总结:其实timer实现定时任务是很简单的,但是在想法开发是很少用到timer,而是用spring的Quartz。我也在网上找到了一些资料,现在总结一下。
1. Java定时器没有持久化机制。
2. Java定时器的日程管理不够灵活(只能设置开始时间、重复的间隔,设置特定的日期、时间等)//这点感同身受
3. Java定时器没有使用线程池(每个Java定时器使用一个线程)//想必在用timer是遇到了吧。
4. Java定时器没有切实的管理方案,你不得不自己完成存储、组织、恢复任务的措施

一下例子是我在myeclipse中创建了一个小项目,仅供参考。

第一步建立web项目(省略)

第二步导入必要包:如下
用到了一下包:
(这九个包我就不多说了,想必大家都知道他的用处。)
第三步:配置相关文件。web.xml、quartz.properties、quartz_job.xml这三个文件。这里我就没用spring的 applicationContext.xml文件来管理了。其实原理都是一样,都是在web启动时监听并启动定时器。配置spring的quartz定 时器有两种方法,一种是你用quartz.properties、quartz_job.xml,另外一种是用spring的 applicationContext.xml。其实在开发的时候我还是比较喜欢前面一种,因为简单、方便,而用spring的 applicationContext.xml里面本来就有各种配置,各种注入,是文件不够清晰(个人见解。呵呵)
(项目中文件的位置,直接放在src目录下)
第四步:web.xml文件配置(监听和启动定时器)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
  <listener>
  <listener-class>
   org.quartz.ee.servlet.QuartzInitializerListener
  </listener-class>
 </listener>
 
 <!--  timer -->
 <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>
 
 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

第五步:配置quartz.properties文件

org.quartz.scheduler.instanceName = TestScheduler
org.quartz.scheduler.instanceId = one

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 2
org.quartz.threadPool.threadPriority = 4

org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
org.quartz.plugin.jobInitializer.fileName = quartz_job.xml

注解:主要主用是启动quartz_job.xml。其余的都是一些配置性能的属性,可以在网上查看。
第六步:配置quartz_job.xml(里面主要配置定时器的一下属性)

<?xml version="1.0" encoding="GBK"?>
<quartz>
<!-- 每1分钟执行一次 -->
 <job>
  <job-detail>
   <name>getDate</name><!-- 表示目标定时器的方法(也就是这个方法要定时的作用)-->
   <group>job</group>
   <job-class>com.timer.util.TimerTask</job-class><!-- 表示上面的getDate()方法路径(即所在的包)-->
  </job-detail>
  <trigger>
   <cron>
    <name>t1</name>
    <group>job</group>
    <job-name>getDate</job-name>
    <job-group>job</job-group>
    <cron-expression>0 0/1 * * * ?</cron-expression><!-- 设置定时器的触发时间即间隔时间(参数形式可以在网上查到自己想要的形式)-->
   </cron>
  </trigger>
 </job>

</quartz>

 

第七步:写用两个类来测试定时器是否好用。

public class TimerTask implements Job {

 private static Logger logger = Logger.getLogger(TimerTask.class);

    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        try {
         TimerOperation.getDate();
        } catch (Exception ex) {
            logger.info(ex.getMessage());
        }
    }

}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class TimerOperation {
 private static Logger logger = Logger.getLogger(TimerOperation.class);
 public static void getDate()
 {
  String strCurrentDateTime = "";
        Date currentDateTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        strCurrentDateTime = formatter.format(currentDateTime);
        logger.info("定时器启动"+strCurrentDateTime);
 }
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

写这两个类就会看出,定时器不能直接调用自己写了定时方法,要先写一个类实现job的接口,然后在实现接口的execute()方法里面调用自己事先写好的定时任务。
好了一个定时器就写好了。运行项目,等待一分钟控制台就会出现

 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics