What is the usage of timer in Java?

In Java, the Timer class is a utility class used for executing scheduled tasks. It allows you to run tasks after a specified delay time, as well as repeat tasks at fixed intervals.

The usage of the Timer class is as follows:

  1. Create a Timer object: Timer timer = new Timer();
  2. Use the schedule() method to execute a task once or at a fixed time interval.
  3. Perform the task once:
    timer.schedule(new TimerTask() {
    @Override
    public void run() {
    // Task logic
    }
    }, delay);

    The delay here is the time in milliseconds.

  4. Execute tasks at fixed time intervals:

    timer.schedule(new TimerTask() {
    @Override
    public void run() {
    // Task logic
    }
    }, delay, period);

    Here, delay represents the delay time and period represents the time interval, both in milliseconds.

  5. Stop the task from executing using the cancel() method: timer.cancel();

It is important to note that the Timer class is single-threaded, so if one task takes too long to execute, it may affect the execution of other tasks. Additionally, the Timer class is not suitable for scenarios that require precise control over execution times because it is subject to system time. Starting from Java 5, it is recommended to use the ScheduledThreadPoolExecutor class instead of the Timer class.

bannerAds