TimerTask vs Thread.sleep vs Handler postDelayed – most accurate to call function every N milliseconds?

What is the most accurate way to call a function every N milliseconds?

  • Thread with Thread.sleep
  • TimerTask
  • Handler with postDelayed

I modified this example using Thread.sleep and it’s not very accurate.

  • How to remove account in AccountManager in Android
  • Editable textview on click
  • How to send binary data with socket.io?
  • Marker Recognition on Android (recognising Rubik's Cubes)
  • Sort a list in ascending order by date from sqlite
  • Stop AppBarLayout scrolling off screen when NestedScrollView is empty
  • I’m developing a music app that will play sounds at a given BPM. I understand it’s impossible to create an entirely accurate metronome and I don’t need to – just looking to find the best way to do this.


    Related posts:

    Android: Vertical ViewPager
    Loading kernel module in Android kernel
    Retrofit Slower response time in real android devices when compared to emulator and web
    How does onLowMemory Work on android?
    Multiple OnClick on Widget for the same Intent
    Equalizer - Effect library not loaded
  • Creating a custom layout for preferences
  • adb can list devices but adb shell/logcat doesn't work
  • Delay call to onQueryTextChange() in SearchView.OnQueryTextListener with SearchView
  • Failed to load module descriptor class: Didn't find class “com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor”
  • Android - Disable screen support x large screens
  • Java optimizations: (Hotspot/Dalvik) Optimization of final method returning a constant?
  • 4 Solutions collect form web for “TimerTask vs Thread.sleep vs Handler postDelayed – most accurate to call function every N milliseconds?”

    There are some disadvantages of using Timer

    • It creates only single thread to execute the tasks and if a task
      takes too long to run, other tasks suffer.
    • It does not handle
      exceptions thrown by tasks and thread just terminates, which affects
      other scheduled tasks and they are never run

    ScheduledThreadPoolExecutor deals properly with all these issues and it does not make sense to use Timer.. There are two methods which could be of use in your case.. scheduleAtFixedRate(…) and scheduleWithFixedDelay(..)

    class MyTask implements Runnable {
      public void run() {
        System.out.println("Hello world");
    ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
    long period = 100; // the period between successive executions
    exec.scheduleAtFixedRate(new MyTask(), 0, period, TimeUnit.MICROSECONDS);
    long delay = 100; //the delay between the termination of one execution and the commencement of the next
    exec.scheduleWithFixedDelay(new MyTask(), 0, delay, TimeUnit.MICROSECONDS);

    On Android you can create Thread with it’s own Handler/Message Queue. It’s quite accurate. When you see Handler documentation you can see, that it was designed for that.

    There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

    They are all the same precision-wise. Java timing precision is subject to the precision and accuracy of system timers and schedulers and is not guaranteed. See Thread.sleep and Object.wait API.

    Using TimerTask for the loop action is the better one. Recommend

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.