Member-only story
How to Schedule a Task with a Fixed Delay in Java? — IT Interview Guide
Java offers various ways to schedule tasks with a fixed delay, which can be extremely useful in a wide range of applications. When you want a task to run repeatedly with a specified delay between executions, Java provides easy-to-use utilities like Timer and ScheduledExecutorService. In this guide, we will explore how to use both methods to schedule tasks with a fixed delay, providing code examples and explanations along the way.
Using Timer and TimerTask
The Timer class in Java can be used to schedule tasks for execution at fixed intervals. A task is generally represented by a TimerTask, which is a subclass of Runnable. The TimerTask runs periodically, and we can specify a fixed delay between executions. Here’s an example of how to schedule a task using Timer:
import java.util.Timer; import java.util.TimerTask; public class FixedDelayTaskWithTimer { public static void main(String[] args) { Timer timer = new Timer(); // Define a task to be executed TimerTask task = new TimerTask() { @Override public void run() { System.out.println("Task executed at: " + System.currentTimeMillis()); } }; // Schedule the task with an initial delay and a fixed delay of 2000 ms (2 seconds) timer.scheduleAtFixedRate(task, 0, 2000); // Initial delay = 0 ms, Fixed delay = 2000 ms…