2015-08-19 71 views
1

我在我的應用程序中有一個條件,那就是如何控制計時器。我想要的是在它剛剛過了15秒之後,啓動函數,並意味着它應該取消,當函數結束時,它會從零開始。如何每15秒運行計時器並取消並重新啓動它

我迄今使用定時器,並給予它1500的延遲和15的重複,但它一次又一次地在啓動該功能完成後,我想我做錯了在這一行:

timer.schedule(doAsynchronousTask, 1500,1); 

這裏是我的計時器的完整代碼

private final Handler handler = new Handler(); 
private final Timer timer = new Timer(); 
private final TimerTask task = new TimerTask() { 

    public void run() { 
     handler.post(new Runnable() { 
      public void run() { 
       launchFunction(); 
      } 
     }); 

    } 
}; 
timer.schedule(doAsynchronousTask, 1500,1); 


void launchFunction(){ 

    Log.d("timer","running"); 
    timer.cancel(); 
} 

但它不能按預期工作,請幫助我。

+0

嘗試'timer.schedule(doAsynchronousTask,1500,1500);' – Rustam

+0

它對我沒有幫助,它每隔一秒啓動一次功能 –

+0

第三個參數表示下一次執行的時間。這意味着第一次延遲之後的每個毫秒都會調用該方法。 – Flown

回答

0

閱讀文檔

/** 
    * Schedule a task for repeated fixed-delay execution after a specific delay. 
    * 
    * @param task 
    *   the task to schedule. 
    * @param delay 
    *   amount of time in milliseconds before first execution. 
    * @param period 
    *   amount of time in milliseconds between subsequent executions. 
    * @throws IllegalArgumentException 
    *    if {@code delay < 0} or {@code period <= 0}. 
    * @throws IllegalStateException 
    *    if the {@code Timer} has been canceled, or if the task has been 
    *    scheduled or canceled. 
    */ 
    public void schedule(TimerTask task, long delay, long period) { 
     if (delay < 0 || period <= 0) { 
      throw new IllegalArgumentException(); 
     } 
     scheduleImpl(task, delay, period, false); 
    } 

設置日程爲timer.schedule(doAsynchronousTask, 15000,15000);和 保持計數器計數,如果達到15倍

相關問題