重试
(attempts uint, sleep time.Duration, f func() error)
| 68 | |
| 69 | // 重试 |
| 70 | func Retry(attempts uint, sleep time.Duration, f func() error) (err error) { |
| 71 | err = f() |
| 72 | if err == nil || attempts == 0 { |
| 73 | return err |
| 74 | } |
| 75 | |
| 76 | for i := 0; i < int(attempts); i++ { |
| 77 | SmartIDELog.DebugF("This is attempt number %v / %v", i+1, attempts) |
| 78 | // calling the important function |
| 79 | err = f() |
| 80 | if err != nil { |
| 81 | warning := fmt.Sprintf("error occured after attempt number %d/%d: %s", i+1, attempts, err.Error()) |
| 82 | SmartIDELog.WarningF(warning) |
| 83 | if i+1 == int(attempts) { |
| 84 | continue |
| 85 | } |
| 86 | |
| 87 | SmartIDELog.DebugF("sleeping for: %v", sleep.String()) |
| 88 | time.Sleep(sleep) |
| 89 | sleep *= 2 |
| 90 | continue |
| 91 | } |
| 92 | break |
| 93 | } |
| 94 | return err |
| 95 | } |