How is Java Timer used?

The Timer class in Java is a timing tool that allows us to execute specific tasks at specified time intervals. It is a class under the java.util package.

Commonly used methods of the Timer class include:

  1. schedule a task to be executed after a specified delay time.
  2. schedule the task to be executed at the specified date and time.
  3. schedule to execute the task after a specified delay time, and then periodically execute the task at a specified time interval.
  4. schedule(TimerTask task, Date firstTime, long period): Start executing the task on the specified date and time, and repeat the task periodically at the specified time interval.
  5. cancel(): Stop the timer and terminate all tasks.

Here is an example using the Timer class:

import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

    @Override
    public void run() {
        // 执行定时任务的逻辑
        System.out.println("Timer task executed.");
    }
}

public class Main {
    public static void main(String[] args) {
        Timer timer = new Timer();
        TimerTask task = new MyTimerTask();

        // 在延迟2秒后执行任务,并每隔3秒重复执行一次
        timer.schedule(task, 2000, 3000);
    }
}

In the above example, a class called MyTimerTask was created by inheriting from the TimerTask class. The run() method was overridden in this class, where the logic for the timer task was defined. In the Main class, a Timer object and a MyTimerTask object were created, and the schedule() method was used to set the execution time and interval of the timer task. In this example, the timer task will start executing after a 2-second delay and will repeat every 3 seconds.

By utilizing the Timer class, we can achieve the execution of repetitive tasks at specific intervals, such as triggering events at specified times or backing up data periodically.

bannerAds