Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Timer Schedule

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?

like image 326
Neji Avatar asked Jan 07 '16 04:01

Neji


People also ask

What is delay and period in Timer Android?

delay - delay in milliseconds before task is to be executed. period - time in milliseconds between successive task executions. (Your IDE should also show it to you automatically)

What is timer in Android Studio?

A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.


1 Answers

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.

like image 137
Kevin Krumwiede Avatar answered Sep 21 '22 13:09

Kevin Krumwiede