3

我有这段代码,我想尝试每小时发送一封电子邮件报告(在示例中为每秒)。如果没有覆盖,请在一小时内重试等。不知何故,我设法打破了 sendUnsendedReports() 中的计时器:它只触发一次。如果我删除对 sendUnsendedReports() 的调用,则计时器工作正常。即使周围有 try-catch 块,计时器也只会触发一次。请指教。

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);
    }
4

3 回答 3

4

似乎有时计时器不能正常工作。替代方法是使用 of Handlerinstead 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);
   }
};

查看此链接以获取更多详细信息。:)

于 2013-01-03T19:03:16.110 回答
3

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) {
    // ...
}
于 2017-03-08T11:31:43.410 回答
1

很明显,您遇到了异常并退出了 Timer run 方法,从而中断了计时器重新启动。

于 2015-04-20T09:35:29.667 回答