Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

Thanks

like image 502
fxfuture Avatar asked Sep 04 '13 04:09

fxfuture


1 Answers

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 {    @Override   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); 
like image 131
Amol Sonawane Avatar answered Sep 26 '22 23:09

Amol Sonawane