-
-
Save laevandus/f1488164d7397be83222815a3715c1a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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