You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
838 B
37 lines
838 B
package retry |
|
|
|
import ( |
|
"time" |
|
) |
|
|
|
// DoWithFixDelay 根据固定延迟重试函数 |
|
func DoWithFixDelay[T any](maxRetryTimes uint32, delay time.Duration, handler func(retryTimes uint32) (T, error)) (r T, lastErr error) { |
|
for retry := range maxRetryTimes { |
|
if retry > 0 { |
|
time.Sleep(delay) |
|
} |
|
r, err := handler(retry) |
|
if err != nil { |
|
lastErr = err |
|
continue |
|
} |
|
return r, nil |
|
} |
|
return |
|
} |
|
|
|
// DoWithStepDelay 根据步进延迟重试函数 1s, 2s, 4s... |
|
func DoWithStepDelay[T any](maxRetryTimes uint32, initialDelay time.Duration, handler func(retryTimes uint32) (T, error)) (r T, lastErr error) { |
|
for retry := range maxRetryTimes { |
|
if retry > 0 { |
|
time.Sleep(time.Duration(1<<(retry-1)) * initialDelay) |
|
} |
|
r, err := handler(retry) |
|
if err != nil { |
|
lastErr = err |
|
continue |
|
} |
|
return r, nil |
|
} |
|
return |
|
}
|
|
|