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


what accurate way call function every n milliseconds?

  • thread thread.sleep
  • timertask
  • handler postdelayed

i modified this example using thread.sleep , it's not accurate.

i'm developing music app play sounds @ given bpm. understand it's impossible create entirely accurate metronome , don't need - looking find best way this.

thanks

there disadvantages of using timer

  • it creates single thread execute tasks , if task takes long run, other tasks suffer.
  • it not handle exceptions thrown tasks , thread terminates, affects other scheduled tasks , never run

scheduledthreadpoolexecutor deals these issues , not make sense use timer.. there 2 methods of use in case.. scheduleatfixedrate(...) , schedulewithfixeddelay(..)

class mytask implements runnable {    @override   public void run() {     system.out.println("hello world");   }  }  scheduledthreadpoolexecutor exec = new scheduledthreadpoolexecutor(1); long period = 100; // period between successive executions exec.scheduleatfixedrate(new mytask(), 0, period, timeunit.microseconds); long delay = 100; //the delay between termination of 1 execution , commencement of next exec.schedulewithfixeddelay(new mytask(), 0, delay, timeunit.microseconds); 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -