I have a scenario where I need to run a certain task at specific interval, however, I want to be able to reset/restart the timer without reinstantiating. Here's my code for better understanding.
private TimerTask beatTask = new TimerTask() {
@Override
public void run() {
beatDetected();
}
};
public void beatDetected() {
timeoutTimer.cancel();
// handle my stuff and restart the timer.
timeoutTimer.schedule(beatTask, 2000);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
(timeoutTimer = new Timer()).schedule(beatTask, 2000);
return Service.START_STICKY;
}
The idea behind this implementation is that beatDetected()
can be called from outside event, in which case the next timer tick should happen from that moment on i.e. the elapsed time for the next task should be reset. However, I only get the first tick, and from that point on, the timer just doesn't work.
I'm not limited to using Timer class, anything that will solve the above scenario will work. I was thinging about using postDelayed, but this code is located in a Service, and I don't really need UI thread aware updates.