2014年9月26日 星期五

Timer

public class TTimer
{
 private static final String TAG = "Timer";
 private static int TIMEOUT = 0; // 單位: 秒
 private Timer mTimer = null;
 private TimerTask mTimerTask = null;
 private static int timercount = 0;
 
 public void setTimer(int time)
 {
  TIMEOUT = time;
 }
 
 public void start()
 {
  Log.i(TAG, "nice-into StartTimer()");
  if (mTimer == null)
   mTimer = new Timer();
  
  if (mTimerTask == null)
  {
   mTimerTask = new TimerTask() {
    @Override
    public void run()
    {
     //Log.i("nice", "timer_test-timercount="+timercount);
     if (timercount == TIMEOUT)
     {
      Log.i(TAG, "TIMEOUT");
      stop();
     }
     else
      timercount++;
    }
   };
  }
  if (mTimer != null && mTimerTask != null)
   mTimer.schedule(mTimerTask, 0, 1000); // one second
 }
 
 public void stop()
 {
  // 因為timer要一直重覆使用,所以先不cancel
  // if (mTimer != null)
  {
   // mTimer.cancel();
   // mTimer = null;
  }
  
  if (mTimerTask != null)
  {
   mTimerTask.cancel();
   mTimerTask = null;
  }
  timercount = 0;
 }
}


使用方法: 在想要的地方呼叫 startTimer(),用TIMEOUT設定停止

ref : snowdream



有些文章提到:
class RemindTask extends TimerTask 
{
    public void run() {
        System.out.println("run task");
    }
}
Timer timer = new Timer();
timer.schedule(new RemindTask(), 15*1000);
 
//  on reset call timer.cancel()
    timer.cancel();
  
//  and then again create a new Timer
    timer = new Timer();
    timer.schedule(new RemindTask(), 15*1000);

But this would mean wastage of thread resources everytime i want to reset.
[That's really not a very big deal, btw. One thread every 15 seconds is paltry. Perhaps another guru can answer in more detail. -Alex]

沒有留言:

張貼留言