Timer技术

来源:互联网 发布:淘宝上靠谱的泰国代购 编辑:程序博客网 时间:2024/05/01 01:53
Class Overview
 java.util.Timer are used to schedule jobs for execution in a background process.
 A single thread is used for the scheduling and this thread has the option of being a daemon thread.
 By calling cancel you can terminate a Timer and its associated thread. 

 All tasks which are scheduled to run after this point are cancelled. 
 Tasks are executed sequentially but are subject to the delays from other tasks run methods. 
 If a specific task takes an excessive amount of time to run it may impact the time at which subsequent tasks may run.
 The TimerTask does not offer any guarantees about the real-time nature of scheduling tasks
 as its underlying implementation relies on the Object.wait(long) method.
 Multiple threads can share a single Timer without the need for their own synchronization.
 
 A Timer can be set to schedule tasks either at a fixed rate or with a fixed period.
 Fixed-period execution is the default.
 The difference between fixed-rate and fixed-period execution is the following: With fixed-rate execution, 
 the start time of each successive run of the task is scheduled in absolute terms without regard for when the previous task run actually took place.
 This can result in a series of bunched-up runs (one launched immediately after another) 
 if busy resources or other system delays prevent the Timer from firing for an extended time.
 With fixed-period execution, each successive run of the task is scheduled relative to the start time of the previous run of the task, 
 so two runs of the task are never fired closer together in time than the specified period.

 Timers主要是用来在后台运行一些任务。可以把Timer设置为守护线程。当调用cancel时所有已经安排的任务都没会被取消。
 Timer中的任务是依次执行的,如果一个任务花很长时间才执行完,那么它就可能影响下一个任务的开始执行的时间。
 TimerTask对任务的实时调度并没有保证,因为作为底层的实现依赖于Object.wait(long)方法。
 注意:守护线程就是一直运行,即使任务完成也不会停止的线程。详细内容请参考《守护线程
 构造函数
Public ConstructorsTimer(String name, boolean isDaemon)
Creates a new named Timer which may be specified to be run as a daemon thread.
Timer(String name)
Creates a new named Timer which does not run as a daemon thread.
Timer(boolean isDaemon)
Creates a new Timer which may be specified to be run as a daemon thread.
Timer()
Creates a new non-daemon Timer.
主要方法

Public Methodsvoidcancel()
Cancels the Timer and all scheduled tasks.
intpurge()
Removes all canceled tasks from the task queue.
voidschedule(TimerTask task, Date when, long period)
Schedule a task for repeated fixed-delay execution after a specific time has been reached.
voidschedule(TimerTask task, long delay, long period)
Schedule a task for repeated fixed-delay execution after a specific delay.
voidschedule(TimerTask task, Date when)
Schedule a task for single execution.
voidschedule(TimerTask task, long delay)
Schedule a task for single execution after a specified delay.
voidscheduleAtFixedRate(TimerTask task, long delay, long period)
Schedule a task for repeated fixed-rate execution after a specific delay has passed.
delay时间后开始执行第一次,从此以后每隔period又开始执行,即使当前还有其他的任务在执行,它也会被调度并执行。
voidscheduleAtFixedRate(TimerTask task, Date when, long period)
Schedule a task for repeated fixed-rate execution after a specific time has been reached.
when时间开始执行第一次,从此以后每隔period又开始执行,即使当前还有其他的任务在执行,它也会被调度并执行。
Timer有两种调度模式fixed-rate(固定调度周期模式),fixed-period(完整执行周期模式)。默认的是fixed-period。
 fixed-period
    public void  schedule  (TimerTask  task, long delay, long period)
  Schedule a task for repeated fixed-delay execution after a specific delay.  schedule  (TimerTask  task, Date  when, long period)
 在delay时间后开始执行第一次,从此以后每隔period又开始执行。如果时间到了,但是当前还有其他的任务在执行,
 它只有等当前任务执行完了,才能被调度并执行。

 fixed-rate:
 public void  scheduleAtFixedRate  (TimerTask  task, long delay, long period)
 public void scheduleAtFixedRate  (TimerTask  task, Date  when, long period)
 在delay时间后开始执行第一次,从此以后每隔period又开始执行,即使当前还有其他的任务在执行,它也会被调度并执行。

因为Timer本身自己是新开了一个线程的,所以为了线程安全,不要在他里面做UI方面的操作。如果需要做UI的话,请通过一个Handler来在UI线程中来进行操作。
关于Handler请参考《关于Handler技术》和《Looper和Handler》.
关于Android的线程模型请参考《Android线程模型
 比如下面的代码就准不正确:
 package com.ray.test;  
 import java.util.Timer;  
 import java.util.TimerTask;  
 import android.app.Activity;  
 import android.os.Bundle;  
 public class JavaTimer extends Activity {  
  Timer timer = new Timer();  
  TimerTask task = new TimerTask(){  
   public void run() {  
   setTitle("hear me?");  
   }  
  };  
  
public void onCreate(Bundle savedInstanceState) {  
   super.onCreate(savedInstanceState);  
   setContentView(R.layout.main);  
   timer.schedule(task, 10000);  
  }  
 } 

 正确的做法应该通过配合基于UI线程的Handler来进行UI的操作。
 正确代码如下:
 package com.ray.test;   
 import java.util.Timer;   
 import java.util.TimerTask;   
 import android.app.Activity;   
 import android.os.Bundle;   
 import android.os.Handler;   
 import android.os.Message;   
 
public class TestTimer extends Activity {   
   Timer timer = new Timer();   
   Handler handler = new Handler(){   
   public void handleMessage(Message msg) {   
    switch (msg.what) {   
    case 1:   
    setTitle("hear me?");   
    break;   
    }   
    super.handleMessage(msg);   
   }   
  };   
  TimerTask task = new TimerTask(){   
   public void run() {   
   Message message = new Message();   
   message.what = 1;   
   handler.sendMessage(message);   
   }   
  };
   
  public void onCreate(Bundle savedInstanceState) {   
   super.onCreate(savedInstanceState);   
   setContentView(R.layout.main);   
   timer.schedule(task, 10000);   
  }   
 }