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 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西