2013-01-03 63 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) { 
    // ... 
}