您还可以使用ScheduledExecutorService
使用 ExecutorService,您可以安排命令在给定延迟后运行,或定期执行。以下示例显示了一个类,该类的方法将 ScheduledExecutorService 设置为每隔十秒发出蜂鸣声,持续一小时:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}