失败重试

object Retry {

  @annotation.tailrec
  def retry[T](n: Int, t: Int)(fn: => T): T = {
    // 最多重试n次,每次间隔t秒
    util.Try { fn } match {
      // 成功则返回结果
      case util.Success(x) => x
      case _ if n > 1 =>
        println("Function executed failed. Retrying...")
        Thread.sleep(1000 * t)
        retry(n - 1, t)(fn)
      // 失败则抛出异常
      case util.Failure(e) => throw e
    }
  }
}

results matching ""

    No results matching ""