How to set a Timer in Java?
To set a timer in Java, you can use the java.util.Timer
class. Here's an example of how to use the Timer
class to schedule a task to run once after a specified delay:
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new MyTask(), 5000); // run the task in 5 seconds
}
static class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("Task executed");
}
}
}
In this example, the MyTask
class extends TimerTask
and overrides the run
method, which contains the code that will be executed when the timer fires. The timer.schedule
method is used to schedule the task to run after a delay of 5 seconds (5000 milliseconds).
You can also use the timer.schedule
method to schedule a task to run repeatedly at a specified interval. For example:
timer.schedule(new MyTask(), 5000, 1000); // run the task every 1 second
This will run the task every 1 second (1000 milliseconds) starting 5 seconds (5000 milliseconds) after the timer
is created.
Note that the Timer
class is a utility class that can be used to schedule tasks to run in the future. It is not a high-precision timer and should not be used for tasks that require precise timing. For more accurate timing, you may want to use the java.util.concurrent.ScheduledThreadPoolExecutor
class or the java.util.concurrent.ScheduledExecutorService
interface.