Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/3f3e68cb4f50a7f5787cca305af22208 to your computer and use it in GitHub Desktop.
Save dacr/3f3e68cb4f50a7f5787cca305af22208 to your computer and use it in GitHub Desktop.
ZIO learning - retrying is possible, very easy and loggable / published by https://github.com/dacr/code-examples-manager #6e276a62-10bb-4563-a5a9-fcb368d3a7e9/c54d3486b4384d1c078e7f4ab2f1e6627500c726
// summary : ZIO learning - retrying is possible, very easy and loggable
// keywords : scala, zio, learning, pure-functional, schedule, decision, exponentialBackOff, jitter, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 6e276a62-10bb-4563-a5a9-fcb368d3a7e9
// created-on : 2021-04-02T15:36:11+02:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.2.2"
//> using dep "dev.zio::zio:2.0.13"
//> using dep "fr.janalyse::zio-worksheet:2.0.13.0"
// ---------------------
import zio.*, zio.worksheet.*
import zio.Schedule.Decision
val logic = for {
content <- ZIO.attempt(scala.io.Source.fromURL("https://mapland.fr/ip")) // just for the example
//content <- ZIO.attempt(scala.io.Source.fromURL("https://mapland.frxx/ip")) // just for the example
} yield content.getLines().mkString("\n") // just for the example
val schedule1 = Schedule.spaced(1.second) && Schedule.recurs(5)
val schedule2 = (Schedule.exponential(1.second) && Schedule.recurs(3)).onDecision((state, out, decision) =>
decision match {
case Decision.Done => ZIO.logInfo("No more retry attempt !")
case Decision.Continue(interval) => ZIO.logInfo(s"Will retry at ${interval.start}")
}
)
val schedule3 = // exponentialBackOffWithJitter
Schedule.exponential(100.millis, 2).jittered && Schedule.recurs(4)
// -------------------------------------------------------------
val logicWithAutoRetries = logic.retry(schedule2)
// -------------------------------------------------------------
val result = logicWithAutoRetries.unsafeRun
println(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment