summaryrefslogtreecommitdiff
path: root/common/retry.go
diff options
context:
space:
mode:
authorKeuin <[email protected]>2022-09-07 02:48:46 +0800
committerKeuin <[email protected]>2022-09-07 02:48:46 +0800
commit8e15d802865ed57db0018c15ea5559c8bd44c01f (patch)
tree48f4632a1ad044bd7f7f8da3ebe2bb03ab4ca6fe /common/retry.go
parent88234ca8fffc4e120adbe0d38071b625ad2f43c7 (diff)
First working version. Just a POC.
Diffstat (limited to 'common/retry.go')
-rw-r--r--common/retry.go35
1 files changed, 35 insertions, 0 deletions
diff --git a/common/retry.go b/common/retry.go
new file mode 100644
index 0000000..6b97ff3
--- /dev/null
+++ b/common/retry.go
@@ -0,0 +1,35 @@
+package common
+
+import (
+ "log"
+ "time"
+)
+
+// AutoRetry retries the supplier automatically, with given time limit and interval.
+// If maximum retry time limit is reached and the supplier still fails,
+// the last error will be returned.
+// If logger is not nil, retry information will be printed to it.
+func AutoRetry[T any](
+ supplier func() (T, error),
+ maxRetryTimes int,
+ retryInterval time.Duration,
+ logger *log.Logger) (T, error) {
+ var err error
+ for i := 0; i < maxRetryTimes; i++ {
+ ret, err := supplier()
+ if err != nil {
+ if logger != nil {
+ logger.Printf("Try %v/%v (sleep %vs): %v\n",
+ i, maxRetryTimes, retryInterval, err)
+ }
+ time.Sleep(retryInterval)
+ continue
+ }
+ // success
+ return ret, nil
+ }
+ if logger != nil {
+ logger.Printf("Max retry times reached, but it still fails. Last error: %v", err)
+ }
+ return *new(T), err
+}