Search code examples
javaandroidhandlerrunnable

Repeating task with handler take more time than interval


I get my data from the server and have to update it every x seconds. I do this using the Handler's postDelayed function.

private long mInterval = 10000;


  Runnable mStatusChecker = new Runnable() {
    @Override
    public void run() {
        try {
            takeServerResponse(); //with vary duration
        }catch (Exception e){
            itsRunning = false;
        } finally {
            if(mHandler!=null)  {
                mHandler.postDelayed(mStatusChecker, mInterval);
            }
        }
    }
};

Sometimes it may take more than X seconds to get new data. What can I do in this situation?

If we need increase interval,how to determine when to do so?


Solution

  • You can calculate the duration time of your job and postDelayed your handler based on the duration time.

    For example:

    startTime = System.currentTimeMillis();
    //your job
    duration = System.currentTimeMillis() - startTime;
    mInterval = mInterval - duration