Skip to content

Commit

Permalink
add retry ❕
Browse files Browse the repository at this point in the history
  • Loading branch information
zanjs committed Jun 25, 2021
1 parent 0baea21 commit c7991ec
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions retry/retry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package retry

import (
"fmt"
"time"
)

// RetryTimes 重试,限制次数
func RetryTimes(name string, tryTimes int, sleep time.Duration, callback func() error) (err error) {
for i := 1; i <= tryTimes; i++ {
err = callback()
if err == nil {
return nil
}
fmt.Printf("[%v]失败,第%v次重试, 错误信息:%s \n", name, i, err)
time.Sleep(sleep)
}
err = fmt.Errorf("[%v]失败,共重试%d次, 最近一次错误:%s \n", name, tryTimes, err)
fmt.Println(err)
return err

}

// RetryDurations 重试,限制时间
func RetryDurations(name string, max time.Duration, sleep time.Duration, callback func() error) (err error) {
t0 := time.Now()
i := 0
for {
err = callback()
if err == nil {
return
}
delta := time.Now().Sub(t0)
if delta > max {
fmt.Printf("[%v]失败,超过最大时间%s, 共重试%d次,最近一次错误: %s \n", name, max, i, err)
return err
}
time.Sleep(sleep)
i++
fmt.Printf("[%v]失败,第%v次重试, 错误信息:%s \n", name, i, err)
}
}

0 comments on commit c7991ec

Please sign in to comment.