您的位置:首页 > 其它

如何正确的使用Timer的schedule()方法?

2014-06-18 21:16 519 查看
public class ButtonDemo01 {
public static void main(String[] args) {
JFrame frame = new JFrame("测试");
Panel panel = new Panel();
frame.add(panel);
//定义五个button数组
JButton[] button = {new JButton("开始"),new JButton("结束"),new JButton("暂停"),new JButton("确定"),new JButton("取消")};
//把五个button数组依次添加到panel中
for (int i = 0; i < button.length; i++) {
panel.add(button[i]);

}
button[0].addActionListener(new ActionListener() {
//button的点击事件
@Override
public void actionPerformed(ActionEvent arg0) {
new ButtonDemo01().timeThread();//调用自定义的定时器方法
}
});
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void timeThread(){
Timer timer = new Timer();
timer.schedule(new TimerTask() {

@Override
public void run() {
// TODO Auto-generated method stub
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
Date time=null;
try {
time= sdf.parse(sdf.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(time);
}
}, 0, 12000);
}
}

timer.schedule(new MyTask(),long time1,long timer2);

今天算是彻底的搞懂了这个曾经让我为之头疼的方法。下面我就重点介绍一下:

第一个参数,是 TimerTask 类,在包:import java.util.TimerTask .使用者要继承该类,并实现 public void run() 方法,因为 TimerTask 类 实现了 Runnable 接口。

第二个参数的意思是,当你调用该方法后,该方法必然会调用 TimerTask 类 TimerTask 类 中的 run() 方法,这个参数就是这两者之间的差值,转换成汉语的意思就是说,用户调用 schedule() 方法后,要等待这么长的时间才可以第一次执行 run() 方法。

第三个参数的意思就是,第一次调用之后,从第二次开始每隔多长的时间调用一次 run() 方法。

[附:]

  技术人员在实现内部办公系统与外部网站一体化的时候,最重要的步骤就是从OA系统读取数据,并且根据网站模板生成最终的静态页面。这里就需要一个定时任务,循环的执行。

  技术人员在写定时任务的时候,想当然的以为Timer.schedule(TimerTask task, long delay)就是重复的执行task。程序运行后发现只运行了一次,总觉得是task里的代码有问题,花了很长时间调试代码都没有结果。

  仔细研读java api,发现:

  schedule(TimerTask task, long delay)的注释:Schedules the specified task for execution after the specified delay。大意是在延时delay毫秒后执行task。并没有提到重复执行

  schedule(TimerTask task, long delay, long period)的注释:Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay。大意是在延时delay毫秒后重复的执行task,周期是period毫秒。

  这样问题就很明确schedule(TimerTask task, long delay)只执行一次,schedule(TimerTask task, long delay, long period)才是重复的执行。关键的问题在于程序员误以为schedule就是重复的执行,而没有仔细的研究API,一方面也是英文能力不够,浏览API的过程中不能很快的理解到含义。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: