`
ipjmc
  • 浏览: 703403 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Timer 与 TimerTask

阅读更多
    使用Timer和TimerTask可以将一个动作延迟一段时间执行,或者周期性的执行某项任务。延迟动作可以很方便的用Handler实现,没必要用Timer。使用Timer和TimerTask周期性的执行某项任务还是非常方便的,它们也是Java本身的特性,可参考文档 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html (这个要比Google的文档详细很多,包括schedule与scheduleAtFixedRate的区别,cancel与purge的作用,一目了然)。

    Timer和TimerTask使用起来也很简单,先定义一个Timer和TimerTask,再调用Timer的schedule方法,并将TimerTask传进去就行了,schedule的方式有很多,这里只把它们简单的列在这里。其中schedule的参数period,都是相对task上一次开始执行时间的,而scheduleAtFixedRate的参数period是相对task第一次开始执行时间的。还可以参考文章: http://blog.csdn.net/weidan1121/article/details/527307


 void	schedule(TimerTask task, Date time) 
         // Schedules the specified task for execution at the specified time.
 void	schedule(TimerTask task, Date firstTime, long period) 
         // Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.
 void	schedule(TimerTask task, long delay) 
         // Schedules the specified task for execution after the specified delay.
 void	schedule(TimerTask task, long delay, long period) 
         // Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
 void	scheduleAtFixedRate(TimerTask task, Date firstTime, long period) 
         // Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
 void	scheduleAtFixedRate(TimerTask task, long delay, long period) 
         // Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.


下面Java代码说明一下使用方法:
package com.ipjmc.timer;

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.SlidingDrawer;

public class TimerDemoActivity extends Activity {
	
    private static final String TAG = "TimerDemo";
	private Timer mTimer = new Timer();
	private TimerTask mTask = new MyTimerTask("A");
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Log.i(TAG, "UI -> " +Thread.currentThread().getId());

        new Timer().schedule(mTask, new Date());
        mTimer.schedule(new MyTimerTask("B"), new Date());
        mTimer.schedule(new MyTimerTask("C"), 2000);
    }
    
    private class MyTimerTask extends TimerTask {

    	private String mName;
    	
    	public MyTimerTask(String name) {
			mName = name;
		}
    	
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.i(TAG, mName + " -> " + Thread.currentThread().getId());
		}
    }
}


[size=medium]    需要注意的是:
    1.每一个Timer会单独开启一个线程,Timer中的费时操作不会阻止UI,但要在TimerTask中进行UI操作的话,需要用Handler或Activity.runOnUiThread()方法。

    2.每个TimerTask只能被schedule一次,第二次会抛出异常
new Timer().schedule(mTask, new Date());
	new Timer().schedule(mTask, new Date()); //E/AndroidRuntime(760): Caused by: java.lang.IllegalStateException: TimerTask is scheduled already

    3.Timer一旦取消,那么它的线程也就没了 (http://disanji.net/2011/04/28/android-timer-tutorial/),不能再在调用Timer的schedule系列函数了,否则会抛出异常。怎么办?再创建一个新的Timer。[/size]
1
1
分享到:
评论
3 楼 ok_lyc 2012-03-15  
好。尤其是后面的注意部分,很好!
2 楼 ipjmc 2011-11-29  
hzl7652 写道
使用
ScheduledExecutorService

不错的建议,thank you。
1 楼 hzl7652 2011-11-27  
使用
ScheduledExecutorService

相关推荐

Global site tag (gtag.js) - Google Analytics