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
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练