使用schedule(Callable<V>, long, TimeUnit)
而不是scheduleAtFixedRate
或scheduleWithFixedDelay
。然后确保您的 Callable在将来的某个时间重新安排自身或新的 Callable 实例。例如:
// Create Callable instance to schedule.
Callable<Void> c = new Callable<Void>() {
public Void call() {
try {
// Do work.
} finally {
// Reschedule in new Callable, typically with a delay based on the result
// of this Callable. In this example the Callable is stateless so we
// simply reschedule passing a reference to this.
service.schedule(this, 5000L, TimeUnit.MILLISECONDS);
}
return null;
}
}
service.schedule(c);
这种方法避免了关闭和重新创建ScheduledExecutorService
.