Skip to content

Instantly share code, notes, and snippets.

@laevandus
Last active February 20, 2022 02:14
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 laevandus/f1488164d7397be83222815a3715c1a1 to your computer and use it in GitHub Desktop.
Save laevandus/f1488164d7397be83222815a3715c1a1 to your computer and use it in GitHub Desktop.
extension Task {
static func retried(times: Int, backoff: TimeInterval = 1.0, priority: TaskPriority? = nil, operation: @escaping @Sendable () async throws -> Success) -> Task where Failure == Error {
Task(priority: priority) {
for attempt in 0..<times {
do {
return try await operation()
}
catch {
let exponentialDelay = UInt64(backoff * pow(2.0, Double(attempt)) * 1_000_000_000)
try await Task<Never, Never>.sleep(nanoseconds: exponentialDelay)
continue
}
}
return try await operation()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment