Created
November 8, 2022 12:49
-
-
Save SkYNewZ/69f09bb63ed1429557aa9121042531fa to your computer and use it in GitHub Desktop.
Go constant backoff retry with max iterations count
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// You can edit this code! | |
// Click here and start typing. | |
package main | |
import ( | |
"errors" | |
"fmt" | |
"time" | |
"github.com/cenkalti/backoff" | |
) | |
type ConstantBackOff struct { | |
Interval time.Duration | |
count int | |
maxCount int | |
} | |
func (b *ConstantBackOff) Reset() {} | |
func (b *ConstantBackOff) NextBackOff() time.Duration { | |
b.count++ | |
if b.count >= b.maxCount { | |
return backoff.Stop | |
} | |
return b.Interval | |
} | |
func NewConstantBackOff(d time.Duration) *ConstantBackOff { | |
return &ConstantBackOff{Interval: d, maxCount: 10} | |
} | |
func main() { | |
// An operation that may fail. | |
operation := func() error { | |
fmt.Println("trying") | |
return errors.New("oops") | |
} | |
err := backoff.Retry(operation, NewConstantBackOff(time.Second*3)) | |
if err != nil { | |
fmt.Printf("got error: %s\n", err) | |
return | |
} | |
// Operation is successful. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment