我有这段代码,我想尝试每小时发送一封电子邮件报告(在示例中为每秒)。如果没有覆盖,请在一小时内重试,等等。不知何故,我设法打破了 sendUnsendReports() 中的计时器:它只触发一次。如果我删除对 sendUnsishedReports() 的调用,则计时器将正常工作。即使周围有 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);
}
Run Code Online (Sandbox Code Playgroud)
似乎有时计时器不能正常工作。另一种方法是使用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);
}
};
Run Code Online (Sandbox Code Playgroud)
查看此链接了解更多详细信息。:)
| 归档时间: |
|
| 查看次数: |
6321 次 |
| 最近记录: |