feat(common): add retry function

This commit is contained in:
Medzik 2021-09-04 11:37:07 +00:00
parent 2006d90d17
commit 857ddb66b0
2 changed files with 40 additions and 0 deletions

37
common/retry.go Normal file
View 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
View File

@ -0,0 +1,3 @@
package main
func main() {}