Josef
Josef

Reputation: 2726

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);  
                     }
                 };

Upvotes: 1

Views: 3194

Answers (2)

Josef
Josef

Reputation: 2726

Seems it works fine with Timer (thanks @Yves Delerm):

Here is the solution if someone need it one day:

private Timer myTimer;
private int TIMERINTERVAL = 3000;

// inside onCreate
myTimer = new Timer();
myTimer.schedule(new TimerTask()
{
    @Override
    public void run()
    {
        myMethod();
    }}, 0, TIMERINTERVAL);



 private void myMethod()
 {
      // Some code
 }

Upvotes: 1

Yves Delerm
Yves Delerm

Reputation: 1045

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);

Upvotes: 3

Related Questions