What's the Scala way to implement a retry-able call like this one?

前端 未结 14 1710
甜味超标
甜味超标 2020-11-29 16:08

Still the newbie in Scala and I\'m now looking for a way to implement the following code on it:

@Override
public void store(InputStream source, String destin         


        
14条回答
  •  死守一世寂寞
    2020-11-29 16:44

    A reusable object/method with a pause between attempts:

    Retry(3, 2 seconds) { /* some code */ }
    

    Code:

    object Retry {
      def apply[A](times: Int, pause: Duration)(code: ⇒ A): A = {
        var result: Option[A] = None
        var remaining = times
        while (remaining > 0) {
          remaining -= 1
          try {
            result = Some(code)
            remaining = 0
          } catch {
            case _ if remaining > 0 ⇒ Thread.sleep(pause.toMillis)
          }
        }
        result.get
      }
    }
    

提交回复
热议问题