java.util.concurrent.ScheduledExecutorService接口是ExecutorService接口的子接口,并支持将来和/或定期执行任务。
ScheduledExecutorService接口的方法
| 序号 | 方法 | 描述 |
|---|---|---|
| 1 | ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) |
创建并执行在给定延迟后启用ScheduledFuture。 |
| 2 | ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) |
创建并执行在给定延迟后启用的单次操作。 |
| 3 | ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) |
创建并执行在给定的初始延迟之后,随后以给定的时间段首先启用的周期性动作; 那就是执行会在initialDelay之后开始,然后是initialDelay + period,然后是initialDelay + 2 * period,等等。 |
| 4 | ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) |
创建并执行在给定的初始延迟之后首先启用的定期动作,随后在一个执行的终止和下一个执行的开始之间给定的延迟。 |
实例
以下TestThread程序显示了基于线程的环境中ScheduledExecutorService接口的使用。
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException {
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> beepHandler =
scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS);
scheduler.schedule(new Runnable() {
@Override
public void run() {
beepHandler.cancel(true);
scheduler.shutdown();
}
}, 10, TimeUnit.SECONDS);
}
static class BeepTask implements Runnable {
public void run() {
System.out.println("beep");
}
}
}
这将产生以下结果 -
beep
beep
beep
beep
beep
