Execute a timeline of actions

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() {
        public void run() {
    }, 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){


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.

Since you are creating the runnable objects in a loop, I guess they are all going to do the same thing? If that's the case, why don't you create one runnable only outside of the loop, and then reuse it in the schedule method?

Need Your Help

Can someone help me figure out this class from documentation?

sockets documentation ipc wt

I have no experience with sockets and I need to implement a process that notifies a user interface of inputs from another process that takes his values from stdin.

How do I bind an ASP.net ajax AccordionPane to an XMLDatasource?

asp.net data-binding asp.net-ajax accordionpane

I've got an angry boss that will beat me down if I waste another day on this :-P Many karma points to the ajax guru who can solve my dilemma.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.