1

I would like to know what exactly the difference is between these two classes, and when should I use each.

I am asking this because I am wondering about this sample code:

mStatusChecker = new Runnable() {
        @Override
        public void run() {
            invalidate();
            mHandler.postDelayed(mStatuschecker, (long) increment * 1000);
        }
    };

If I put the mHandler.postDelayed line of code before invalidate(), the Runnable is executed at almost double the speed. I am wondering if a Timer could be used instead to fix this problem.

3 Answers3

0

Timer is 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.

Haroun Hajem
  • 5,223
  • 3
  • 26
  • 39
0

It's better to user Timer functionality if you need timer functionality like task needing to be run at regular intervals.

Java java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals. Java Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization.

https://www.journaldev.com/1050/java-timer-timertask-example

Pradip Karki
  • 662
  • 1
  • 8
  • 21
0

Timer is not an Android class, it's a Java SDK class included in the Android SDK for compatibility with legacy code. It does not play well with the Android component lifecycle and requires extra code to interact with the UI. In short, do not use Timer on Android.

Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82