Execute a timeline of actions
<p>i have a bunch of actions that need to be executed in an android app after an exact waiting period.</p>

<p>action 1: start after 1000ms<br>
action 2: start after 2000ms<br>
action 3: start after 3000ms</p>

<p>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.</p>

<p>does anyone have experience with a similar task and could give me a hint what the best method is?</p>

<p>oh, this will of course run in an AsyncTask.</p>

<p>thx
simon</p>

<pre><code>int[] times = new int[]{ 1000, 2000, 3000 };

// 1. use ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(times.length);
for(int i = 0; i &lt; 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 &lt; max){
    int t = times[i];
    long diff = System.currentTimeMillis() - start;
    if(diff &gt;= t){
        System.out.println("loop");
        i++;
    }
}
</code></pre>
