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
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短