I’m trying to execute a TimerTask every x time with independence of the task time execution.
I tried alot of things and I stoped here:
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);
}
}
}
}
As you can see I have a condition before I send to db so somtimes I won’t do anything so my records time should be in jumps of 5 minutes.
Here is the output:
15:08
15:22
15:40
The first 2 times are false, why?
The reason that I tagged android is because I do it on an android system and maybe it has some effects.
Rather than sleeping inside your run method like that, you should use scheduleAtFixedRate. This will ensure your task runs at fixed intervals (approximately every 30 seconds) regardless of how long the task takes to execute.