Java如何使用计时器创建计划任务?

本示例说明如何使用TimerandTimerTask类创建用于计划任务的简单类。

package org.nhooo.example.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerExample extends TimerTask {
    private DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");

    public static void main(String[] args) {
        // 创建一个TimerTask实现器实例。
        TimerTask task = new TimerExample();

        // 创建一个新计时器以将TimerExample实例安排在
        // 每5000毫秒(5秒)的周期性时间并启动
        // 立即
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(task, new Date(), 5000);
    }

    /**
     * This method is the implementation of a contract defined in the 
     * TimerTask class. This in the entry point of the task execution.
     */
    public void run() {
        // 为了简化示例,我们只打印当前时间。
        System.out.println(formatter.format(new Date()));
    }
}

这是上面的代码片段打印的结果:

03:10:38 PM
03:10:43 PM
03:10:48 PM
03:10:53 PM
03:10:58 PM