Skip to content
This repository has been archived by the owner on May 13, 2022. It is now read-only.

keisku/backoff

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

backoff

A simple exponential backoff counter.

The algorithm is based on google.

Github issues Github forks Github stars

LOGO

install

go get github.com/kskumgk63/backoff

Examples

no options

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 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

abort backoff loop

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)
	}
}

debug mode on

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...
.
.
.

change debug printer

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.

About

A simple exponential backoff counter.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages