i have a bunch of actions that need to be executed in an android app after an exact waiting period.
action 1: start after 1000ms
action 2: start after 2000ms
action 3: start after 3000ms
i developed 2 different approaches to achieve this. one with a ScheduledThreadPoolExecutor and one with a loop. the ScheduledThreadPoolExecutor results in an OutOfMemoryException if there are too many actions to execute and feels also not so precise. the version with the loop works actually quite well and feels precise, but uses of course an awful lot of CPU power.
does anyone have experience with a similar task and could give me a hint what the best method is?
oh, this will of course run in an AsyncTask.
thx
simon
int[] times = new int[]{ 1000, 2000, 3000 };
// 1. use ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(times.length);
for(int i = 0; i < times.length; i++){
ex.schedule(new Runnable() {
@Override
public void run() {
System.out.println("timer");
}
}, times[i], TimeUnit.MILLISECONDS);
}
// 2. use loop
int i = 0;
int max = times.length;
long start = System.currentTimeMillis();
while(i < max){
int t = times[i];
long diff = System.currentTimeMillis() - start;
if(diff >= t){
System.out.println("loop");
i++;
}
}
Your option 1 is significantly better than your option two because you aren’t needlessly churning as much CPU time as you can get to run it.