mirror of
https://github.com/MedzikUser/go-utils.git
synced 2024-08-15 03:26:56 +00:00
feat(common): add retry function
This commit is contained in:
parent
2006d90d17
commit
857ddb66b0
2 changed files with 40 additions and 0 deletions
37
common/retry.go
Normal file
37
common/retry.go
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
/*
|
||||||
|
If there is an error in the performed function, it will be restarted, this process will be repeated the given number of times
|
||||||
|
|
||||||
|
e.g.
|
||||||
|
|
||||||
|
err := Retry(3, 5*time.Second, connectToDB)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
Log.Error(err)
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
func Retry(attempts int, sleep time.Duration, f func() error) (err error) {
|
||||||
|
for i := 0; ; i++ {
|
||||||
|
err = f()
|
||||||
|
if err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if i >= (attempts - 1) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
time.Sleep(sleep)
|
||||||
|
sleep *= 2
|
||||||
|
|
||||||
|
Log.Error("Retrying after error: ", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
|
||||||
|
}
|
3
main.go
Normal file
3
main.go
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
func main() {}
|
Loading…
Reference in a new issue