1

I write a simple AsyncTask which:

    @Override
    protected Void doInBackground(Void... params) {
    for (int i = 0; i <= 99; i++) {
        long time = System.currentTimeMillis();
        try {
            //Wait for 6ms
            Thread.sleep(6);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long diff = System.currentTimeMillis() - time;
        Log.d(TAG, "Row "i + " is DONE with timeDiff=" + diff + "ms vs. waitTime=" + waitTime + "ms");
        publishProgress(i);
    }
}

It works well in some of test devices until I try on LG devices (Nexus 4, G3): time to sleep seems longer than I think. After checking log, I see in normal case, timeDiff is 6ms or 7ms; while with LG devices, timeDiff is mostly > 40ms.

Also try to use SystemClock.sleep() but no luck.

Could anyone please suggest me how to fix it? Any help would be appreciated!

anticafe
  • 6,816
  • 9
  • 43
  • 74
  • 2
    It's hard to suggest a better solution if we don't know why you're using `Thread.sleep()` in the first place. – Kevin Krumwiede Nov 27 '15 at 07:40
  • @KevinKrumwiede In fact I have a Speed Control in UI to change `waitTime`. The larger `waitTime`, the slower Thread must sleep. – anticafe Nov 27 '15 at 07:46
  • are you sure it isn't your publishProgress(i) call that is taking the extra time as you are counting that also. – Kuffs Nov 27 '15 at 07:54
  • 1
    Thread has no guarantee to call at same time it may or may not be call at time, – Singh_Nindi Nov 27 '15 at 07:57
  • @Kuffs Sure I confirm. >40ms is just time of `Thread.sleep()`, not count time of `publishprogress()` – anticafe Nov 27 '15 at 07:59
  • That is not reflected in the code you have posted which is timing the other calls also – Kuffs Nov 27 '15 at 08:01
  • 1
    As @Singh_Nindi states, Thread are not guaranteed to be precise. See: http://stackoverflow.com/questions/23169557/thread-sleep-and-precise-timing - Try to use a `ScheduledExecutorService` if you want more accurate measurements. On a side-note: why are you trying to halt execution for 6 ms? What is the purpose of that? Scheduling execution of code are in most cases more preferred as you can rely on the OS to execute the code on the right time. – Darwind Nov 27 '15 at 18:49
  • 1
    Is the `AsyncTask` doing anything other than creating a delay? Is this supposed to be simulating some work? – Kevin Krumwiede Nov 28 '15 at 02:33

1 Answers1

1

Alternate solution is use Handler for wait.

Handler handler = new Handler(); 
handler.postDelayed(new Runnable() { 
     public void run() { 
          //call after delay

     } 
}, 2000); 
Mayur Sakhiya
  • 326
  • 2
  • 14