Zima
Zima

Reputation: 176

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?

Upvotes: 1

Views: 99

Answers (2)

MohammadReza Eram
MohammadReza Eram

Reputation: 568

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

Upvotes: 2

Amit pandey
Amit pandey

Reputation: 1195

your handler used to call the server response after 10 sec.But Its all depend own your internet speed to get the data from server that's the reason its take long time

Upvotes: 1

Related Questions