用java.util.Timer定时执行任务
如果要在程序中定时执行任务,可以使用java.util.Timer这个类实现。使用Timer类需要一个继承了java.util.TimerTask的类。TimerTask是一个虚类,需要实现它的run方法,实际上是他implements了Runnable接口,而把run方法留给子类实现。
下面是我的一个例子:
class Worker extends TimerTask {
public void run() {
System.out.println("我在工作啦!");
}
}
Timer类用schedule方法或者scheduleAtFixedRate方法启动定时执行,schedule 重载了四个版本,scheduleAtFixedRate重载了两个。每个方法的实现都不同,下面是每个方法的说明:
schedule
public void schedule(TimerTask task,
long delay)
Schedules the specified task for execution after the specified delay.
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
Throws:
IllegalArgumentException - if delay is negative, or delay +
System.currentTimeMillis() is negative.
IllegalStateException- if task was already scheduled or cancelled, or timer was cancelled.
说明:该方法会在设定的延时后执行一次任务。