Stacking Delays On Tasks

One of my favorite task queue tricks is to add a stacking delay whenever multiple tasks need to be added. Here’s a sample piece of code::

TaskOptions task = TaskOptions.Builder.withUrl("/example");
task.param(parameter_name, parameter_value);
//Stacking delay here. Every subsequent task is delayed 
//an extra 5 minutes.
task.countdownMillis((1000 * 5) + (i * 5 * 60 * 1000));
Queue queue = QueueFactory.getDefaultQueue();
queue.add(task);

Notice the i variable in the countdownMillis function. The countdown function tells the task to delay a certain amount of milliseconds.

Placing this code within a for loop (and with i as the loop counter) causes each added task to be delayed for 5 seconds, plus an additional 5 minutes over the previous task. To see how it works, consider how the i variable is processed: the first task (when i = 0) will execute in 5 seconds (due to the 1000 times 5 part – 5,000 milliseconds translates into 5 seconds). The second task (when i = 1) will execute in 5 minutes & 5 seconds (1000 * 5 + 1 * 5 * 60 * 1000 turns into 5,000 + 1 * 300,000 which is 305,000 milliseconds, which is also 5 minutes, 5 seconds). The third task will wait for 605,000 milliseconds, which is 10 minutes plus 5 seconds, and so forth.

Staggering tasks like this can make an application run smoother and with fewer spikes in resource usage.