我有一个函数,它接受一个任务并运行它 n 次,每次运行之间有一个设定的间隔。它应该返回一个 Future ,当任务完成时,它可以用来获取任务的结果。
这是我目前所拥有的:
public <V> Future<V> runTaskAsynchronously(ITask<V> task, int numOfTimes, long sleep) {
ScheduledExecutorService ses = Executors.newScheduledThreadPool(numOfTimes);
Callable<V> callable = () -> {
return task.call();
};
}
每个任务都是这个接口的一个实现:
public interface ITask<T> {
/**
* A task if complete if its objective
* has been met through an invokation
* of the 'call' method.
*
*/
public boolean isComplete();
/**
* Does the actual work and returns
* a result.
*
*/
public T call();
}
如何完成runTaskAsynchronously方法的实现?我曾尝试使用 executorService.scheduleAtFixedRate 方法,但这仅适用于 Runnables 而不适用于 Callables。
我查看了 Scheduling a Callable at a fixed rate,但 BlockingQueue 实现在这里不起作用,因为我需要返回一个未来。