scheduledthreadpoolexecutor 的 schedulewithfixeddelay 方法用于创建一个周期性任务,该任务在每次执行完成后等待指定的固定延迟时间再开始下一次执行。要使用它,你需要实例化一个 scheduledthreadpoolexecutor,调用其 schedulewithfixeddelay 方法并传入 runnable、初始延迟和周期参数。该方法会立即返回一个 scheduledfuture 对象,你可以用它来取消任务或检查状态。

如何配置初始延迟和执行周期
scheduleWithFixedDelay 接受三个参数:第一个是 Runnable 类型的任务体,第二个是初始延迟(initial delay),第三个是任务完成到下次启动之间的间隔(period)。初始延迟是指从提交任务到第一次执行开始的时间,而 period 是指上一次任务执行结束到下一次任务执行开始之间的等待时间。如果初始延迟为 0,任务将立即开始执行。如果任务执行时间超过周期,下一次执行将在当前任务结束后立即开始,不会重叠。

import java.util.concurrent.*;
public class FixedDelayExample {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Runnable task = () -> {
System.out.println("Task started at " + System.currentTimeMillis());
try {
Thread.sleep(2000); // 模拟任务耗时
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Task finished at " + System.currentTimeMillis());
};
long initialDelay = 1000; // 1秒后首次执行
long period = 3000; // 每次结束后等待3秒再开始下一次
ScheduledFuture<?> future = executor.scheduleWithFixedDelay(task, initialDelay, period, TimeUnit.MILLISECONDS);
// 保持主线程运行以便观察输出
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
future.cancel(false);
executor.shutdown();
}
}
如何处理任务异常与线程池关闭
当周期性任务抛出未捕获的异常时,scheduleWithFixedDelay 会自动停止后续的执行,但线程池本身仍然处于活跃状态。这意味着如果你不处理异常,任务会在第一次失败后终止,且不会再次触发。为了避免这种情况,建议在 Runnable 内部使用 try-catch 块包裹业务逻辑,或者通过自定义 RejectedExecutionHandler 或重写 afterExecute 方法来监控和处理异常。此外,当不再需要任务时,应调用 ScheduledFuture.cancel() 并关闭线程池,以防止资源泄漏。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.*;
public class ExceptionHandlingExample {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Runnable faultyTask = () -> {
System.out.println("Executing task...");
if (Math.random() > 0.5) {
throw new RuntimeException("Simulated failure");
}
System.out.println("Task completed successfully.");
};
// 设置初始延迟为0,周期为2秒
executor.scheduleWithFixedDelay(faultyTask, 0, 2000, TimeUnit.MILLISECONDS);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
}
}


















