8

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?

Neji
  • 6,591
  • 5
  • 43
  • 66

2 Answers2

7

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.

Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82
  • Perfect!!, just what i needed. I solved my problem using handler already, but was curious to find what went wrong when used timer in first place! :) – Neji Jan 11 '16 at 09:02
0

Use this code.. this will help you..

Timer t;
seconds = 10;

public void startTimer() {
        t = new Timer();
        //Set the schedule function and rate
        t.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (seconds == 0) {
                            t.cancel();
                           seconds = 10;
                      // DO SOMETHING HERE AFTER 10 SECONDS
                       Toast.makeText(this,"Time up",Toast.LENGTH_SHORT).show();
                        }
                        seconds -= 1;
                    }
                });
            }
        }, 0, 1000);
    }
Uttam Panchasara
  • 5,735
  • 5
  • 25
  • 41