Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handler.postDelayed(Runnable) vs CountdownTimer

Sometimes we need to delay a code before it runs.

This is doable by the Handler.postDelayed(Runnable) or CountdownTimer.

Which one is better in terms of performance?

See the sample code below

Handler

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                 //DO SOMETHING
            }
        }, 1000);

CountDownTimer

        new CountDownTimer(1000, 1000) {
            public void onFinish() {
                 //DO SOMETHING
            }
            public void onTick(long millisUntilFinished) {}
        }.start();
like image 220
JayVDiyk Avatar asked Feb 19 '16 05:02

JayVDiyk


2 Answers

The Handler should offer you better performances as CountDownTimer contains itself a Handler as you can see here.

like image 63
E-Kami Avatar answered Oct 13 '22 02:10

E-Kami


I agree that Handler is offering a better performance. But on a side note, you should keep in mind that CountDownTimer object will be destroyed after completed. A Handler will continue to exist after finished. If you only need a temporary timer then CountDownTimer is preferable. Otherwise, use a Handler.

like image 38
minh bo Avatar answered Oct 13 '22 01:10

minh bo