A simple exponential backoff counter.
The algorithm is based on google.
go get github.com/kskumgk63/backoff
Repeat alwaysErr()
at intervals of backoff time until the timeout occurs.
func alwaysErr() error {
return errors.New("internal server error")
}
func main() {
cmd := backoff.NewCommander()
if timeoutErr := cmd.Exec(alwaysErr); timeoutErr != nil {
fmt.Println(timeoutErr)
}
}
After 65s, this message is printed. No messages during exponential backoff loop.
Ends the exponential backoff because of timeout
Change the timeout value to 10 seconds.
func alwaysErr() error {
return errors.New("internal server error")
}
func main() {
cmd := backoff.NewCommander(
backoff.Timeout(5 * time.Second),
)
if timeoutErr := cmd.Exec(alwaysErr); timeoutErr != nil {
fmt.Println(timeoutErr)
}
}
After 5s, this message is printed. No messages during exponential backoff loop.
Ends the exponential backoff because of timeout
The backoff loop is aborted when a specific error occurs.
This example below prints nothing, exit 0.
func alwaysErr() error {
return errors.New("internal server error")
}
func main() {
cmd := backoff.NewCommander(
backoff.AbortLoop(func(err error) {
return err.Error() == "internal server error"
}),
)
if timeoutErr := cmd.Exec(alwaysErr); timeoutErr != nil {
fmt.Println(timeoutErr)
}
}
if debug mode is on, prints errors when repeating alwaysErr()
func alwaysErr() error {
return errors.New("internal server error")
}
func main() {
cmd := backoff.NewCommander(
backoff.DebugModeOn(),
)
cmd.Exec(alwaysErr)
}
internal server error
waiting 2.020000s...
internal server error
waiting 4.564000s...
internal server error
waiting 8.586000s...
internal server error
waiting 16.869000s...
.
.
.
func alwaysErr() error {
return errors.New("internal server error")
}
func main() {
cmd := backoff.NewCommander(
backoff.Timeout(10*time.Second),
backoff.DebugModeOn(),
backoff.DebugPrint(func(err error) {
fmt.Printf("[ERR] %+v\n", err)
}),
)
if timeoutErr := cmd.Exec(alwaysErr); timeoutErr != nil {
fmt.Println(timeoutErr)
}
}
You can change a debug printer!
[ERR] internal server error
waiting 2.088000s...
[ERR] internal server error
waiting 4.904000s...
[ERR] internal server error
waiting 8.212000s...
Ends the exponential backoff because of timeout
See more options.