计时器可以提供运行基于时间的工作任务的功能,在计时器的管理下,特定的任务可在某一时间运行一次,也可以按指定的时间间隔反复运行。在众多厂商提供的计时器中应用得比较多的有以下三种:
一、 java.util.Timer
Sun JDK 提供的一种轻量级的计时器。
二、Commonj Timer
IBM 和 BEA 联合制定和推出的一种适用于 J2EE 环境的计时器。
三、WebSphere Application Server Scheduler
IBM WebSphere Application Server 提供的一种功能强大的计时器。
java.util.Timer
java.util.Timer 是 Sun JDK 提供的一种计时器,用于使后台线程按计划执行指定任务,这些任务可以被执行一次,也可以被定期执行。每个 Timer 对象对应一个后台线程,顺序地执行所有计时器任务。如果完成某个计时器任务的时间太长,那么它会“独占”计时器的任务执行线程,从而可能延迟后续任务的执行。对 Timer 对象最后的引用完成并且所有未处理的任务都已执行完成后,计时器的任务执行线程会正常终止(并且成为垃圾回收的对象)。以下为一个使用 java.util.Timer 的例子:
Java代码
view plaincopy to clipboardprint?
importjava.util.Timer;
importjava.util.TimerTask;
publicclassTimerTest {
Timer timer;
publicTimerTest(intseconds) {
timer = newTimer();
timer.schedule(newTimerTestTask(), seconds*1000);
}
classTimerTestTaskextendsTimerTask {
publicvoidrun() {
System.out.println("In TimerTestTask, execute run method.");
timer.cancel();
}
}
publicstaticvoidmain(String args[]) {
System.out.println("Prepare to schedule task.");
newTimerTest(2);
System.out.println("Task scheduled.");
}
}
importjava.util.Timer;
importjava.util.TimerTask;
publicclassTimerTest {
Timer timer;
publicTimerTest(intseconds) {
timer = newTimer();
timer.schedule(newTimerTestTask(), seconds*1000);
}
classTimerTestTaskextendsTimerTask {
publicvoidrun() {
System.out.println("In TimerTestTask, execute run method.");
timer.cancel();
}
}
publicstaticvoidmain(String args[]) {
System.out.println("Prepare to schedule task.");
newTimerTest(2);
System.out.println("Task scheduled.");
}
}
view plaincopy to clipboardprint?
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
Timer timer;
public TimerTest(int seconds) {
timer = new Timer();
timer.schedule(new TimerTestTask(), seconds*1000);
}
class TimerTestTask extends TimerTask {
public void run() {
System.out.println("In TimerTestTask, execute run method.");
timer.cancel();
}
}
public static void main(String args[]) {
System.out.println("Prepare to schedule task.");
new TimerTest(2);
System.out.println("Task scheduled.");
}
}
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
Timer timer;
public TimerTest(int seconds) {
timer = new Timer();
timer.schedule(new TimerTestTask(), seconds*1000);
}
class TimerTestTask extends TimerTask {
public void run() {
System.out.println("In TimerTestTask, execute run method.");
timer.cancel();
}
}
public static void main(String args[]) {
System.out