Android Timer Schedule

Neji picture Neji · Jan 7, 2016 · Viewed 7.7k times · Source

Following is the code snippet which I am using in my project to schedule a task

mTimer = new Timer();
mTimer.schedule(new TimerTask() {

 @Override
 public void run() {
  //Do Something
 }

}, interval, interval);

This works fine. I get event after mentioned interval. But this fails to send any event if date is set smaller than current from settings.

Does any one know why this behavior is happening?

Answer

Kevin Krumwiede picture Kevin Krumwiede · Jan 11, 2016

Timer fails when you change the system clock because it's based on System.currentTimeMillis(), which is not monotonic.

Timer is not an Android class. It's a Java class that exists in the Android API to support existing non-Android libraries. It's almost always a bad idea to use a Timer in your new Android code. Use a Handler for timed events that occur within the lifetime of your app's activities or services. Handler is based on SystemClock.uptimeMillis(), which is monotonic. Use an Alarm for timed events that should occur even if your app is not running.