[英]Trying to execute a TimerTask every x time
我每隔x次嘗試執行一次TimerTask,獨立於任務時間執行。 我嘗試了很多東西,我停在這里:
new Timer().schedule(new Send(),new Date();
...
Class Send extends TimerTask
{
boolean shouldRun = true;
public void run()
{
long start = System.currentTimeMillis();
while(shouldRun)
{
if(condition)
//send to db
long next = start + 300000;
try{
Thread.sleep(next - System.currentTimeMillis());
start = next;
}catch(InterruptedException e){
System.out.println(e);
}
}
}
}
正如你所看到的,在我發送到db之前我有一個條件,所以有時我不會做任何事情所以我的記錄時間應該是5分鍾的跳躍。
這是輸出:15:08 15:22 15:40前2次都是假的,為什么?
我標記android的原因是因為我在Android系統上執行它可能它有一些效果。
你應該使用scheduleAtFixedRate,而不是在你的run方法中睡覺。 這將確保您的任務以固定的時間間隔(大約每30秒)運行,無論任務執行的時間長短。
new Timer().scheduleAtFixedRate(new Send(),new Date(),30000);
...
Class Send extends TimerTask
{
boolean shouldRun = true;
public void run()
{
long start = System.currentTimeMillis();
while(shouldRun)
{
if(condition)
//send to db
}
}
}
你可以用這個:
public void toCallAsynchronous() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
//YOUR CODE HERE
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 2000); // execute in every 2000 second
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.