Timer 和 TimerTask 详解

来源:互联网 发布:淘宝网折叠床双 编辑:程序博客网 时间:2024/04/29 14:05

1.概览
Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。
TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。
简单的一个例程1:

import java.util.Timer;
import java.util.TimerTask;
/**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/
public class Reminder {
    Timer timer;
    public Reminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    }
    class RemindTask extends TimerTask {
        public void run() {
            System.out.println("Time's up!");
            timer.cancel(); //Terminate the timer thread
        }
    }
    public static void main(String args[]) {
        System.out.println("About to schedule task.");
        new Reminder(5);
        System.out.println("Task scheduled.");
    }
}
运行这个小例子,你会首先看到:
About to schedule task.
Task scheduled.
Time's up!

这里用schedule方法,第一个参数是TimerTask对象,第二个参数表示开始执行前的延时时间(单位是milliseconds,这里定义了5000)。还有一种方法可以指定任务的执行时间,如下例,指定任务在11:01 p.m.执行:
 //Get the Date corresponding to 11:01:00 pm today.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
Date time = calendar.getTime();
timer = new Timer();
timer.schedule(new RemindTask(), time);

 

 

实例2:

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;

/**
 * @author vincent
 */

public class TimerTest {

 public static void main(String[] args) {
  Timer t = new Timer();
  
  //在5秒之后执行TimerTask的任务
  t.schedule(new TimerTask(){
     public void run()
     {System.out.println("this is task you do1");}
    },5*1000);


  //在Date指定的特定时刻之后执行TimerTask的任务
  Date d1 = new Date(System.currentTimeMillis()+1000);
  t.schedule(new TimerTask(){
   public void run()
   {System.out.println("this is task you do2");}
  },d1);


  //在Date指定的特定时刻之后,每隔1秒执行TimerTask的任务一次
  Date d2 = new Date(System.currentTimeMillis()+1000);
  t.schedule(new TimerTask(){
   public void run()
   {System.out.println("this is task you do3");}
  },d2,1*1000);


  //在3秒之后,每隔1秒执行TimerTask的任务一次
  t.schedule(new TimerTask(){
   public void run()
   {System.out.println("this is task you do4");}
  },3*1000,1*1000);
  
  //在3秒之后,绝对每隔2秒执行TimerTask的任务一次

  t.scheduleAtFixedRate(new TimerTask(){
   public void run()
   {System.out.println("this is task you do6");}
  },3*1000,2*1000);
 }

 

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线程有关。
 
3.反复执行一个任务
先看一个例子:
public class AnnoyingBeep {
    Toolkit toolkit;
    Timer timer;
    public AnnoyingBeep() {
        toolkit = Toolkit.getDefaultToolkit();
        timer = new Timer();
        timer.schedule(new RemindTask(),
               0,        //initial delay
               1*1000);  //subsequent rate
    }
    class RemindTask extends TimerTask {
        int numWarningBeeps = 3;
        public void run() {
            if (numWarningBeeps > 0) {
                toolkit.beep();
                System.out.println("Beep!");
                numWarningBeeps--;
            } else {
                toolkit.beep();
                System.out.println("Time's up!");
                //timer.cancel(); //Not necessary because we call System.exit
                System.exit(0);   //Stops the AWT thread (and everything else)
            }
        }
    }
    ...
}
执行,你会看到如下输出:
Task scheduled.
Beep!     
Beep!      //one second after the first beep
Beep!      //one second after the second beep
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方法。

 

4.进一步分析schedule和scheduleAtFixedRate

(1)

schedulescheduleAtFixedRate的区别在于,如果指定开始执行的时间在当前系统运行时间之前,scheduleAtFixedRate会把已经过去的时间也作为周期执行,而schedule不会把过去的时间算上。 

4.
  System.out.println("aaaaaaaaa");
  Date d3 = new Date(System.currentTimeMillis() + 5000 );
  t.scheduleAtFixedRate(new TimerTask(){
   public void run()
   {System.out.println("this is task you do8");}
  },  d3,4*1000);
  System.out.println("bbbbbbbbb");

 

aaaaaaaaa
bbbbbbbbb

this is task you do8
this is task you do8

...

 

 

 

5.一些注意的问题
每一个Timer仅对应唯一一个线程。
Timer不保证任务执行的十分精确。
Timer类的线程安全的。

 1.Date d3 = new Date(System.currentTimeMillis() - 5000);
  t.scheduleAtFixedRate(new TimerTask(){
   public void run()
   {System.out.println("this is task you do8");}
  }, d3,4*1000); //运行会立即执行两次run 

 

 2.Date d3 = new Date(System.currentTimeMillis() - 1000);
  t.scheduleAtFixedRate(new TimerTask(){
   public void run()
   {System.out.println("this is task you do8");}
  }, d3,4*1000); //运行会立即执行1次run

 

 

 3. t.scheduleAtFixedRate(new TimerTask(){
   public void run()
   {System.out.println("this is task you do8");}
  }, new Date(),4*1000); //运行会立即执行1次run