看到别人代码中使用到Timer和TimerTask来实现定时或者循环调用,自己使用了下,一个循环的timer不能暂停,cancel后就不能用了,必须要重新创建一个对象才合理,为此我觉得使用起来也不是很合理,不过貌似网上也不推荐使用这个java原生的东东。作为知识点,转两篇文章下来吧。
http://blog.chinaunix.net/uid-26524139-id-3152128.html
Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。
TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。
schedule的意思(时间表、进度表)
timer.schedule(new MyTask(event.getServletContext()), 0, 60*60*1000);
第一个参数"new MyTask(event.getServletContext())":
是 TimerTask 类,在包:import java.util.TimerTask .使用者要继承该类,并实现 public void run() 方法,因为 TimerTask 类实现了 Runnable 接口。
第二个参数"0"的意思是:(0就表示无延迟)
当你调用该方法后,该方法必然会调用 TimerTask 类 TimerTask 类 中的 run() 方法,这个参数就是这两者之间的差值,转换成汉语的意思就是说,用户调用 schedule() 方法后,要等待这么长的时间才可以第一次执行 run() 方法。
第三个参数"60*60*1000"的意思就是:
(单位是毫秒60*60*1000为一小时)
(单位是毫秒3*60*1000为三分钟)
第一次调用之后,从第二次开始每隔多长的时间调用一次 run() 方法
例子:
public Timer createJobber(TimerTask o, String cronExpress) throws Exception {
Timer timer = new Timer();
timer.schedule(o, 0, Integer.parseInt(cronExpress));
return timer;
}
http://dev.10086.cn/cmdn/bbs/thread-59000-1-1.html
| myTask2.start(0,1); try{ Thread.sleep(6000); } catch(InterruptedException e){ } myTask1.end(); myTask2.end();//程序结束时用cancel()结束Timer } public void start(int delay, int internal) { myTimer.schedule(this, delay * 1000, internal * 1000); //利用timer.schedule方法 } public void end(){ myTimer.cancel(); } } 输出: First task Second task Second task Second task First task Second task Second task Second task |