Search code examples
androidrunnable

Correct handler postdelay time


I'm facing an issue about executing something at a specific time. My app has an Runnable class that executes a method at a specific time. The problem is that sometimes the Runnable needs 4000 ms instead of 3000 ms to execute. Is there a way to correct this ?

The code:

private Handler myhandler;

//onCreateMethod
myhandler = new Handler();


//runnable class        
    private Runnable myRunnable = new Runnable() {
        public void run() {     
            methodToExecute();
            myhandler.postDelayed(this, 3000);  
                     }
                 };

Solution

  • If you need more precision, do not use Handler.postDelayed, but rather use a Timer

    Anyway, as stated in the comment, android is not realtime os, but you should get more precision, like between 2900 and 3100 ms.

    For instance :

    Timer.schedule(timerTask, 3000);