2013-01-03 62 views
2

我有這段代碼,我想嘗試每小時發送一次電子郵件報告(在這個例子中是每秒一次)。如果沒有覆蓋範圍,請在一小時內再試一次等​​等。不知何故,我設法在sendUnsendedReports()中打破計時器:它只觸發一次。如果我刪除了對sendUnsendedReports()的調用,那麼定時器運行完美。即使使用try-catch塊,計時器也只會觸發一次。請指教。Android定時器只會觸發一次

private void createAndScheduleSendReport() { 
     delayedSendTimer = new Timer(); 
     delayedSendTimer.schedule(new TimerTask() { 
      @Override 
      public void run() { 
       Log.w("UrenRegistratie", "Try to send e-mail..."); 
       try{ 
        sendUnsendedReports(); 
       } 
       catch(Exception e){ 
        // added try catch block to be sure of uninterupted execution 
       } 
       Log.w("UrenRegistratie", "Mail scheduler goes to sleep."); 
      } 
     }, 0, 1000); 
    } 
+1

找到......所以你這是在做sendunsendedreports()?似乎是那個你應該看的地方。 –

+1

...至少你應該記錄你(可能)遇到的任何異常。 –

+0

不應該不可能打破計時器?在sendUnsendedReports()中,我將關閉飛行模式,休眠幾秒鐘,產生一些xml報告並嘗試使用gmail發送它並再次打開飛行模式。 – Harmen

回答

3

似乎有時計時器不能正常工作,因爲它應該是。替代方案是使用Handler而不是TimerTask

你可以用它喜歡:

private Handler handler = new Handler(); 
handler.postDelayed(runnable, 1000); 

private Runnable runnable = new Runnable() { 
    @Override 
    public void run() { 
     try{ 
       sendUnsendedReports(); 
      } 
      catch(Exception e){ 
       // added try catch block to be sure of uninterupted execution 
      } 
     /* and here comes the "trick" */ 
     handler.postDelayed(this, 1000); 
    } 
}; 

退房this link瞭解更多詳情。 :)

+1

這不是一個答案本身,只是一個鏈接到另一個頁面...你應該在這裏提供鏈接的內容(以防止鏈接腐爛)或張貼此評論。 – Sam

+2

@Sam:感謝您的建議。我相應地編輯了我的答案。 :) –

+0

@RaviBhatt wauw甚至一個適合我的代碼的例子,好:) – Harmen

0

很明顯,您遇到了異常並退出Timer運行方法,從而中斷了定時器重新啓動。

1

schedule()可以以各種方式進行調用,具體取決於您希望任務執行一次還是定期執行。

要執行的任務只有一次:

timer.schedule(new TimerTask() { 
    @Override 
    public void run() { 
    } 
}, 3000); 

要3秒後執行任務的每一秒。

timer.schedule(new TimerTask() { 
    @Override 
    public void run() { 
    } 
}, 3000, 1000); 

更多示例用法可以在方法頭

public void schedule(TimerTask task, Date when) { 
    // ... 
} 

public void schedule(TimerTask task, long delay) { 
    // ... 
} 

public void schedule(TimerTask task, long delay, long period) { 
    // ... 
} 

public void schedule(TimerTask task, Date when, long period) { 
    // ... 
}