Skip to content

Instantly share code, notes, and snippets.

@SkYNewZ
Created November 8, 2022 12:49
Show Gist options
  • Save SkYNewZ/69f09bb63ed1429557aa9121042531fa to your computer and use it in GitHub Desktop.
Save SkYNewZ/69f09bb63ed1429557aa9121042531fa to your computer and use it in GitHub Desktop.
Go constant backoff retry with max iterations count
// 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