Timer和TimerTask详解

开发 后端
本文主要介绍了Timer和TimerTask这两个工具,而以下内容根据The JavaTM Tutorial和相关API doc翻译整理,以供日后参考:

以下内容根据 The JavaTM Tutorial 和相关API doc翻译整理,以供日后参考:

1.概览

Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。

TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。

简单的一个例程:

  1. import java.util.Timer;  
  2. import java.util.TimerTask;  
  3.  
  4. /**  
  5. * Simple demo that uses java.util.Timer to schedule a task to execute  
  6. * once 5 seconds have passed.  
  7. */ 
  8.  
  9. public class Reminder {  
  10.     Timer timer;  
  11.  
  12.     public Reminder(int seconds) {  
  13.         timer = new Timer();  
  14.         timer.schedule(new RemindTask(), seconds*1000);  
  15.     }  
  16.  
  17.     class RemindTask extends TimerTask {  
  18.         public void run() {  
  19.             System.out.println("Time's up!");  
  20.             timer.cancel(); //Terminate the timer thread  
  21.         }  
  22.     }  
  23.  
  24.     public static void main(String args[]) {  
  25.         System.out.println("About to schedule task.");  
  26.         new Reminder(5);  
  27.         System.out.println("Task scheduled.");  
  28.     }  
  29. }  

运行这个小例子,你会首先看到:

About to schedule task.

5秒钟之后你会看到:

Time's up!

这个小例子可以说明一些用Timer线程实现和计划执行一个任务的基础步骤:

  •  实现自定义的TimerTask的子类,run方法包含要执行的任务代码,在这个例子里,这个子类就是RemindTask。
  • 实例化Timer类,创建计时器后台线程。
  • 实例化任务对象 (new RemindTask()).
  • 制定执行计划。这里用schedule方法,***个参数是TimerTask对象,第二个参数表示开始执行前的延时时间(单位是milliseconds,这里定义了5000)。还有一种方法可以指定任务的执行时间,如下例,指定任务在11:01 p.m.执行:
  1. //Get the Date corresponding to 11:01:00 pm today.  
  2. Calendar calendar = Calendar.getInstance();  
  3. calendar.set(Calendar.HOUR_OF_DAY, 23);  
  4. calendar.set(Calendar.MINUTE, 1);  
  5. calendar.set(Calendar.SECOND, 0);  
  6. Date time = calendar.getTime();  
  7.  
  8. timer = new Timer();  
  9. timer.schedule(new RemindTask(), time); 

2.终止Timer线程

默认情况下,只要一个程序的timer线程在运行,那么这个程序就会保持运行。当然,你可以通过以下四种方法终止一个timer线程:

调用timer的cancle方法。你可以从程序的任何地方调用此方法,甚至在一个timer task的run方法里。

让timer线程成为一个daemon线程(可以在创建timer时使用new Timer(true)达到这个目地),这样当程序只有daemon线程的时候,它就会自动终止运行。

当timer相关的所有task执行完毕以后,删除所有此timer对象的引用(置成null),这样timer线程也会终止。

调用System.exit方法,使整个程序(所有线程)终止。

Reminder的例子使用了***种方式。在这里不能使用第二种方式,因为这里需要程序保持运行直到timer的任务执行完成,如果设成daemon,那么当main线程结束的时候,程序只剩下timer这个daemon线程,于是程序不会等timer线程执行task就终止了。

有些时候,程序的终止与否并不只与timer线程有关。举个例子,如果我们使用AWT来beep,那么AWT会自动创建一个非daemon线程来保持程序的运行。

  1. import java.util.Timer;  
  2. import java.util.TimerTask;  
  3. import java.awt.Toolkit;  
  4.  
  5. /**  
  6. * Simple demo that uses java.util.Timer to schedule a task to execute  
  7. * once 5 seconds have passed.  
  8. */ 
  9.  
  10. public class ReminderBeep {  
  11.     Toolkit toolkit;  
  12.     Timer timer;  
  13.  
  14.     public ReminderBeep(int seconds) {  
  15.         toolkit = Toolkit.getDefaultToolkit();  
  16.         timer = new Timer();  
  17.         timer.schedule(new RemindTask(), seconds*1000);  
  18.     }  
  19.  
  20.     class RemindTask extends TimerTask {  
  21.         public void run() {  
  22.             System.out.println("Time's up!");  
  23.     toolkit.beep();  
  24.     //timer.cancel(); //Not necessary because we call System.exit  
  25.     System.exit(0);   //Stops the AWT thread (and everything else)  
  26.         }  
  27.     }  
  28.  
  29.     public static void main(String args[]) {  
  30. System.out.println("About to schedule task.");  
  31.         new ReminderBeep(5);  
  32. System.out.println("Task scheduled.");  
  33.     }  

3.反复执行一个任务

先看一个例子:

  1. public class AnnoyingBeep {  
  2.     Toolkit toolkit;  
  3.     Timer timer;  
  4.  
  5.     public AnnoyingBeep() {  
  6.         toolkit = Toolkit.getDefaultToolkit();  
  7.         timer = new Timer();  
  8.         timer.schedule(new RemindTask(),  
  9.                0,        //initial delay  
  10.                1*1000);  //subsequent rate  
  11.     }  
  12.  
  13.     class RemindTask extends TimerTask {  
  14.         int numWarningBeeps = 3;  
  15.  
  16.         public void run() {  
  17.             if (numWarningBeeps > 0) {  
  18.                 toolkit.beep();  
  19.                 System.out.println("Beep!");  
  20.                 numWarningBeeps--;  
  21.             } else {  
  22.                 toolkit.beep();   
  23.                 System.out.println("Time's up!");  
  24.                 //timer.cancel(); //Not necessary because we call System.exit  
  25.                 System.exit(0);   //Stops the AWT thread (and everything else)  
  26.             }  
  27.         }  
  28.     }  
  29.     ...  
  30. }   

执行,你会看到如下输出:

  1. Task scheduled.  
  2. Beep!   
  3. Beep! //one second after the first beep  
  4. Beep! //one second after the second beep  
  5. Time's up! //one second after the third beep 

这里使用了三个参数的schedule方法用来指定task每隔一秒执行一次。如下所列为所有Timer类用来制定计划反复执行task的方法 :

  •  schedule(TimerTask task, long delay, long period)
  • schedule(TimerTask task, Date time, long period)
  • scheduleAtFixedRate(TimerTask task, long delay, long period)
  • scheduleAtFixedRate(TimerTask task, Date firstTime, long period)

当计划反复执行的任务时,如果你注重任务执行的平滑度,那么请使用schedule方法,如果你在乎的是任务的执行频度那么使用scheduleAtFixedRate方法。 例如,这里使用了schedule方法,这就意味着所有beep之间的时间间隔至少为1秒,也就是说,如果有一个beap因为某种原因迟到了(未按计划执行),那么余下的所有beep都要延时执行。如果我们想让这个程序正好在3秒以后终止,无论哪一个beep因为什么原因被延时,那么我们需要使用scheduleAtFixedRate方法,这样当***个beep迟到时,那么后面的beep就会以最快的速度紧密执行(***限度的压缩间隔时间)。

4.进一步分析schedule和scheduleAtFixedRate

(1)2个参数的schedule在制定任务计划时, 如果指定的计划执行时间scheduledExecutionTime<=systemCurrentTime,则task会被立即执行。scheduledExecutionTime不会因为某一个task的过度执行而改变。

(2)3个参数的schedule在制定反复执行一个task的计划时,每一次执行这个task的计划执行时间随着前一次的实际执行时间而变,也就是scheduledExecutionTime(第n+1次)=realExecutionTime(第n次)+periodTime。也就是说如果第n次执行task时,由于某种原因这次执行时间过长,执行完后的systemCurrentTime>=scheduledExecutionTime(第n+1次),则此时不做时隔等待,立即执行第n+1次task,而接下来的第n+2次task的scheduledExecutionTime(第n+2次)就随着变成了realExecutionTime(第n+1次)+periodTime。说白了,这个方法更注重保持间隔时间的稳定。

(3)3个参数的scheduleAtFixedRate在制定反复执行一个task的计划时,每一次执行这个task的计划执行时间在最初就被定下来了,也就是scheduledExecutionTime(第n次)=firstExecuteTime+n*periodTime;如果第n次执行task时,由于某种原因这次执行时间过长,执行完后的systemCurrentTime>=scheduledExecutionTime(第n+1次),则此时不做period间隔等待,立即执行第n+1次task,而接下来的第n+2次的task的scheduledExecutionTime(第n+2次)依然还是firstExecuteTime+(n+2)*periodTime这在***次执行task就定下来了。说白了,这个方法更注重保持执行频率的稳定。

5.一些注意的问题

  • 每一个Timer仅对应唯一一个线程。
  • Timer不保证任务执行的十分精确。
  • Timer类的线程安全的。

原文链接:http://blog.csdn.net/xiaozhang0731/article/details/5688345

【编辑推荐】

  1. 在JDK和Eclipse下Java Applet的编写和运行方式
  2. Java中的Enum的使用与分析
  3. 按权重选取目标的Java算法
  4. 通用Java文件上传和下载组件的设计与实现
  5. 5种JavaScript调用函数的方法
责任编辑:林师授 来源: xiaozhang0731的博客
相关推荐

2009-09-07 05:50:59

C# Timer用法

2009-06-16 11:39:17

JBoss端口修改

2009-06-18 10:27:42

Spring Time

2021-07-30 15:50:54

Python定时器JavaScrip

2009-07-17 16:32:34

Timer对象Swing

2009-08-25 13:38:35

C# Timer组件

2012-05-08 13:58:37

SharePoint

2011-05-31 16:50:35

Android 线程

2010-01-28 09:45:16

Android Tim

2010-02-03 15:58:51

C++ timer

2023-10-07 08:26:40

多线程数据传递数据共享

2009-12-25 10:59:08

WPF Timer

2010-01-22 15:25:46

VB.NET Time

2009-06-22 16:19:45

JavaBeansEJBPOJO

2009-06-11 10:00:50

Glassfish安装GlassFish配置

2009-07-21 13:43:53

ASP和JSP比较

2017-04-26 08:51:36

MongoDB集群实战

2019-01-21 15:57:29

VLANVXLAN局域网

2011-04-02 09:17:38

2009-07-09 14:01:22

JVM工作原理
点赞
收藏

51CTO技术栈公众号