Java Timer Class Tutorial: Schedule Tasks

In Java, you can use the java.util.Timer class to create a timer. Here is a simple example code demonstrating how to use the Timer class to execute scheduled tasks.

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

public class TimerExample {
    public static void main(String[] args) {
        Timer timer = new Timer();

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Task executed at: " + System.currentTimeMillis());
            }
        };

        // 设置定时任务,在延迟1000毫秒后执行任务,然后每隔2000毫秒执行一次
        timer.schedule(task, 1000, 2000);
    }
}

In the example above, a Timer object is first created, followed by a TimerTask object where the run() method is overridden to define the task to be executed. Finally, the schedule() method is used to set the timing and interval for the scheduled task.

When this code is executed, it will output the current time information every two seconds. In real-world applications, the tasks to be executed can be written based on specific needs.

bannerAds