Posts

Showing posts from November, 2024

Java's ScheduledExecutorService example

Example of Java's ScheduledExecutorService to run a block of code once (with a delay) or repeatedly at fixed rate or fixed delay. ScheduledExecutorService can be a single threaded executor (used to execute in a coordinated way) or can be multi threaded executor (used to execute in parallel) import java.util.concurrent.Executors ; import java.util.concurrent.ScheduledExecutorService ; import java.util.concurrent.TimeUnit ; public class ExampleScheduledExecutor implements AutoCloseable { private final ScheduledExecutorService executorService = Executors . newSingleThreadScheduledExecutor (); // use newScheduledThreadPool() for running with multiple threads in parallel // private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); public ExampleScheduledExecutor ( long initialDelay , long fixedDelay ) { executorService .schedule(() -> executeOnlyOnce(), initialDelay , TimeUnit . SECONDS ); executorService .scheduleAtFixedR...