免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2369 | 回复: 0
打印 上一主题 下一主题

Timer 与 TimerTask [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-11-27 14:43 |只看该作者 |倒序浏览
  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


Java代码
  1. 1.void    schedule(TimerTask task, Date time)   
  2. 2.        // Schedules the specified task for execution at the specified time.   
  3. 3.void    schedule(TimerTask task, Date firstTime, long period)   
  4. 4.        // Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.   
  5. 5.void    schedule(TimerTask task, long delay)   
  6. 6.        // Schedules the specified task for execution after the specified delay.   
  7. 7.void    schedule(TimerTask task, long delay, long period)   
  8. 8.        // Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.   
  9. 9.void    scheduleAtFixedRate(TimerTask task, Date firstTime, long period)   
  10. 10.        // Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.   
  11. 11.void    scheduleAtFixedRate(TimerTask task, long delay, long period)   
  12. 12.        // Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.  
  13. void        schedule(TimerTask task, Date time)
  14.          // Schedules the specified task for execution at the specified time.
  15. void        schedule(TimerTask task, Date firstTime, long period)
  16.          // Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.
  17. void        schedule(TimerTask task, long delay)
  18.          // Schedules the specified task for execution after the specified delay.
  19. void        schedule(TimerTask task, long delay, long period)
  20.          // Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
  21. void        scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
  22.          // Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
  23. void        scheduleAtFixedRate(TimerTask task, long delay, long period)
  24.          // Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
复制代码
下面Java代码说明一下使用方法:

Java代码
  1. 1.package com.ipjmc.timer;   
  2. 2.  
  3. 3.import java.util.Date;   
  4. 4.import java.util.Timer;   
  5. 5.import java.util.TimerTask;   
  6. 6.  
  7. 7.import android.app.Activity;   
  8. 8.import android.os.Bundle;   
  9. 9.import android.util.Log;   
  10. 10.import android.widget.SlidingDrawer;   
  11. 11.  
  12. 12.public class TimerDemoActivity extends Activity {   
  13. 13.      
  14. 14.    private static final String TAG = "TimerDemo";   
  15. 15.    private Timer mTimer = new Timer();   
  16. 16.    private TimerTask mTask = new MyTimerTask("A");   
  17. 17.      
  18. 18.    @Override  
  19. 19.    public void onCreate(Bundle savedInstanceState) {   
  20. 20.        super.onCreate(savedInstanceState);   
  21. 21.        setContentView(R.layout.main);   
  22. 22.  
  23. 23.        Log.i(TAG, "UI -> " +Thread.currentThread().getId());   
  24. 24.  
  25. 25.        new Timer().schedule(mTask, new Date());   
  26. 26.        mTimer.schedule(new MyTimerTask("B"), new Date());   
  27. 27.        mTimer.schedule(new MyTimerTask("C"), 2000);   
  28. 28.    }   
  29. 29.      
  30. 30.    private class MyTimerTask extends TimerTask {   
  31. 31.  
  32. 32.        private String mName;   
  33. 33.           
  34. 34.        public MyTimerTask(String name) {   
  35. 35.            mName = name;   
  36. 36.        }   
  37. 37.           
  38. 38.        @Override  
  39. 39.        public void run() {   
  40. 40.            // TODO Auto-generated method stub   
  41. 41.            try {   
  42. 42.                Thread.sleep(1000);   
  43. 43.            } catch (InterruptedException e) {   
  44. 44.                // TODO Auto-generated catch block   
  45. 45.                e.printStackTrace();   
  46. 46.            }   
  47. 47.            Log.i(TAG, mName + " -> " + Thread.currentThread().getId());   
  48. 48.        }   
  49. 49.    }   
  50. 50.}  
  51. package com.ipjmc.timer;

  52. import java.util.Date;
  53. import java.util.Timer;
  54. import java.util.TimerTask;

  55. import android.app.Activity;
  56. import android.os.Bundle;
  57. import android.util.Log;
  58. import android.widget.SlidingDrawer;

  59. public class TimerDemoActivity extends Activity {
  60.        
  61.     private static final String TAG = "TimerDemo";
  62.         private Timer mTimer = new Timer();
  63.         private TimerTask mTask = new MyTimerTask("A");
  64.        
  65.     @Override
  66.     public void onCreate(Bundle savedInstanceState) {
  67.         super.onCreate(savedInstanceState);
  68.         setContentView(R.layout.main);

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

  70.         new Timer().schedule(mTask, new Date());
  71.         mTimer.schedule(new MyTimerTask("B"), new Date());
  72.         mTimer.schedule(new MyTimerTask("C"), 2000);
  73.     }
  74.    
  75.     private class MyTimerTask extends TimerTask {

  76.             private String mName;
  77.            
  78.             public MyTimerTask(String name) {
  79.                         mName = name;
  80.                 }
  81.            
  82.                 @Override
  83.                 public void run() {
  84.                         // TODO Auto-generated method stub
  85.                         try {
  86.                                 Thread.sleep(1000);
  87.                         } catch (InterruptedException e) {
  88.                                 // TODO Auto-generated catch block
  89.                                 e.printStackTrace();
  90.                         }
  91.                         Log.i(TAG, mName + " -> " + Thread.currentThread().getId());
  92.                 }
  93.     }
  94. }
复制代码
[size=medium]    需要注意的是:
    1.每一个Timer会单独开启一个线程,Timer中的费时操作不会阻止UI,但要在TimerTask中进行UI操作的话,需要用Handler或Activity.runOnUiThread()方法。

    2.每个TimerTask只能被schedule一次,第二次会抛出异常

Java代码
  1. 1.new Timer().schedule(mTask, new Date());   
  2. 2.    new Timer().schedule(mTask, new Date()); //E/AndroidRuntime(760): Caused by: java.lang.IllegalStateException: TimerTask is scheduled already  
  3. new Timer().schedule(mTask, new Date());
  4.         new Timer().schedule(mTask, new Date()); //E/AndroidRuntime(760): Caused by: java.lang.IllegalStateException: TimerTask is scheduled already

  5.     3.Timer一旦取消,那么它的线程也就没了 (http://disanji.net/2011/04/28/android-timer-tutorial/),
复制代码
不能再在调用Timer的schedule系列函数了,否则会抛出异常。怎么办?再创建一个新的Timer。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP