我希望能够轮询API端点直到达到某个条件。我预计它会在几秒钟到一分钟内达到这个条件。我有一个调用端点并返回
假设我有一个具有以下签名的函数:
Future
的方法。有没有办法将Future
链接在一起,以便每隔n
毫秒轮询此端点,并在t
次尝试后放弃?假设我有一个具有以下签名的函数:
def isComplete(): Future[Boolean] = ???
在我看来,最简单的方法是将所有操作都变成阻塞式的:
def untilComplete(): Unit = {
for { _ <- 0 to 10 } {
val status = Await.result(isComplete(), 1.seconds)
if (status) return Unit
Thread.sleep(100)
}
throw new Error("Max attempts")
}
但这种方法可能会占用所有线程,而且它不是异步的。我还考虑了递归的实现:
def untilComplete(
f: Future[Boolean] = Future.successful(false),
attempts: Int = 10
): Future[Unit] = f flatMap { status =>
if (status) Future.successful(Unit)
else if (attempts == 0) throw new Error("Max attempts")
else {
Thread.sleep(100)
untilComplete(isComplete(), attempts - 1)
}
}
然而,我担心调用栈会达到最大值,因为这不是尾递归。
有没有更好的方法来解决这个问题?
编辑:我正在使用akka。