2016-09-06 123 views
0

我有Timer,我使用方法scheduleAtFixedRate以某種固定速率安排任務。問題是,在一些行動後,我想完成/取消此前計劃的任務。在不停止計時器的情況下停止TimerTask

我知道,我可以使用.cancel().purge(),但將取消/完成我的計時器,這是一件好事,我不想。我只想完成任務。

你們有沒有人知道如何做到這一點?

這是我的代碼(我有作爲類的字段創建Timer

receiveTimer.scheduleAtFixedRate(new TimerTask() { 
     @Override 
     public void run() { 

      int fileSize=(int)fileSizeToReceive; 
      int actual= totalReceived; 

      ((Notification.Builder) mBuilderReceive).setContentText("Receiving "+actualNameToReceive); 
      ((Notification.Builder) mBuilderReceive).setProgress(fileSize, actual, false); 
      mNotifyManager.notify(id, ((Notification.Builder) mBuilderReceive).getNotification()); 
     } 
    },0,500);//delay, interval 

回答

1

剛請提及您的TimerTask,以便您隨時可以撥打cancel()

TimerTask上調用cancel()不會停止Timer

例如,聲明你的任務:

TimerTask task; 

初始化,並安排它:

task = new TimerTask() { 
    @Override 
    public void run() { 
     int fileSize=(int)fileSizeToReceive; 
     int actual= totalReceived; 

     ((Notification.Builder) mBuilderReceive) 
      .setContentText("Receiving "+actualNameToReceive); 
     ((Notification.Builder) mBuilderReceiver) 
      .setProgress(fileSize, actual, false); 
     mNotifyManager.notify(id, ((Notification.Builder) mBuilderReceive) 
      .getNotification()); 
    } 
}; 

receiveTimer.scheduleAtFixedRate(task, 0, 500); 

要停止它,你只需要調用cancel()的任務實例:

task.cancel(); 
+0

它工作,謝謝! –

1

boolean isStop = false;

receiveTimer.scheduleAtFixedRate(new TimerTask() { 
     @Override 
     public void run() { 

      if(!isStop){ 

      int fileSize=(int)fileSizeToReceive; 
      int actual= totalReceived; 

      ((Notification.Builder) mBuilderReceive).setContentText("Receiving "+actualNameToReceive); 
      ((Notification.Builder) mBuilderReceive).setProgress(fileSize, actual, false); 
      mNotifyManager.notify(id, ((Notification.Builder) mBuilderReceive).getNotification()); 
      } 
     } 
    },0,500);//delay, interval 

當你不想執行的代碼設置isStop = true