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 妈妈祝福语简短16字
17 农民朋友发财祝福语简短
18 嫂子生日的祝福语简短