A simple solution would be to make use of Java's ScheduledExecutorService
and use the scheduleAtFixedRate
method.
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit)
Creates and executes a periodic action that becomes enabled first after the given initial
delay, and subsequently with the given delay between the termination of one execution
and the commencement of the next. If any execution of the task encounters an exception,
subsequent executions are suppressed. Otherwise, the task will only terminate
via cancellation or termination of the executor.
Parameters:
command - the task to execute
initialDelay - the time to delay first execution
delay - the delay between the termination of one execution
and the commencement of the next
unit - the time unit of the initialDelay and delay parameters
Here is a simple example that demonstrates how the delays work:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Example {
private static long START_TIME;
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);
START_TIME = System.currentTimeMillis();
Runnable task1 = printTask("T1");
Runnable task2 = printTask("T2");
Runnable task3 = printTask("T3");
Runnable task4 = printTask("T4");
scheduledExecutorService.scheduleAtFixedRate(task1, 3, 3, TimeUnit.SECONDS);
scheduledExecutorService.scheduleAtFixedRate(task2, 5, 3, TimeUnit.SECONDS);
scheduledExecutorService.scheduleAtFixedRate(task3, 0, 5, TimeUnit.SECONDS);
scheduledExecutorService.scheduleAtFixedRate(task4, 2, 2, TimeUnit.SECONDS);
Thread.sleep(15000);
scheduledExecutorService.shutdown();
scheduledExecutorService.awaitTermination(6000, TimeUnit.SECONDS);
}
private static Runnable printTask(String prefix) {
return () -> System.out.println(prefix + ": " + (System.currentTimeMillis() - START_TIME));
}
}
Example output (for 1 run). Your results should be similar but might not be the exact same. Each task is first executed after the initialDelay
in the provided unit
, and then are scheduled to occur after each delay
:
T3: 38
T4: 2039
T1: 3039
T4: 4040
T2: 5040
T3: 5040
T1: 6039
T4: 6040
T2: 8040
T4: 8040
T1: 9039
T3: 10040
T4: 10040
T2: 11040
T1: 12039
T4: 12040
T2: 14039
T4: 14039