该服务根据选择的策略创建延迟(纳秒)序列。
有两种策略:
类型 | 描述 |
---|---|
恒定 | 该策略实现恒定退避。 |
指数 [默认] | 指数退避是一种策略,在这种策略中,您会增加重试之间的延迟。 |
/// Constant delay between retries
case constant(
retry : UInt = 5,
duration: DispatchTimeInterval,
timeout: DispatchTimeInterval
)
/// Exponential backoff is a strategy in which you increase the delays between retries
case exponential(
retry : UInt = 3,
multiplier: Double = 2.0, // power exponent
duration: DispatchTimeInterval,
timeout: DispatchTimeInterval
)
final class ViewModel : ObservableObject{
func constant() async {
let policy = RetryService(strategy: .constant())
for delay in policy{
try? await Task.sleep(nanoseconds: delay)
// do something
}
}
func exponential() async {
let policy = RetryService(
strategy: .exponential(
retry: 5,
multiplier: 2,
duration: .seconds(1),
timeout: .seconds(5)
)
)
for delay in policy{
try? await Task.sleep(nanoseconds: delay)
// do something
}
}
}
struct ContentView: View {
@StateObject var model = ViewModel()
var body: some View {
VStack {
Button("constatnt") { Task { await model.constant() } }
Button("exponential") { Task { await model.exponential() } }
}
.padding()
.task {
await model.exponential()
}
}
}
带有抖动的指数退避。抖动为退避增加一些随机性,以在时间上分散重试。 更多信息请参考:Exponential Backoff And Jitter