Skip to content

Instantly share code, notes, and snippets.

@hanishi
Created December 15, 2025 08:39
Show Gist options
  • Select an option

  • Save hanishi/8599684e217b8a36f3a1ce27622fa33c to your computer and use it in GitHub Desktop.

Select an option

Save hanishi/8599684e217b8a36f3a1ce27622fa33c to your computer and use it in GitHub Desktop.
import org.apache.pekko.actor.{Actor, Timers, Props}
import scala.concurrent.duration.*
object RetryActor {
case object DoWork
case class RetryWork(attempt: Int)
case object WorkSucceeded
case object WorkFailed
private case object RetryTimerKey
}
class RetryActor extends Actor with Timers {
import RetryActor._
val MaxRetries = 3
def receive: Receive = {
case DoWork =>
doWork()
// Schedule retry in case it fails
scheduleRetry(1)
case RetryWork(attempt) =>
if (attempt > MaxRetries) {
println(s"Exhausted $MaxRetries retries")
} else {
println(s"Retry attempt $attempt")
doWork()
scheduleRetry(attempt + 1)
}
case WorkSucceeded =>
// Cancel pending retry
timers.cancel(RetryTimerKey)
println("Success - cancelled retry")
case WorkFailed =>
// Let scheduled retry handle it
println("Failed - retry scheduled")
}
private def scheduleRetry(attempt: Int): Unit = {
val delay = (1 << attempt).seconds // 2, 4, 8... seconds
timers.startSingleTimer(RetryTimerKey, RetryWork(attempt), delay)
}
private def doWork(): Unit = {
// Simulate async work that sends WorkSucceeded or WorkFailed back
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment