Skip to content

Commit

Permalink
feat(misc/retry): add execution retrier
Browse files Browse the repository at this point in the history
  • Loading branch information
saitofun committed Jun 12, 2024
1 parent 77a4814 commit 0c52e6e
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
39 changes: 39 additions & 0 deletions misc/retry/retry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package retry

import (
"log"
"reflect"
"time"

"github.com/xoctopus/x/reflectx"
)

type Retry struct {
Repeats int
Interval time.Duration
}

func (r *Retry) SetDefault() {
reflectx.Set(reflect.ValueOf(r), reflect.ValueOf(Default))
}

func (r Retry) Do(exec func() error) (err error) {
if r.Repeats <= 0 {
return exec()
}
for i := 0; i < r.Repeats; i++ {
if err = exec(); err != nil {
log.Printf("retry in %s [err: %v]", r.Interval, err)
time.Sleep(r.Interval)
continue
}
break
}
return
}

var Default = &Retry{3, 3 * time.Second}

func Do(retry *Retry, exec func() error) error {
return retry.Do(exec)
}
32 changes: 32 additions & 0 deletions misc/retry/retry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package retry_test

import (
"testing"

g "github.com/onsi/gomega"
"github.com/pkg/errors"

"github.com/xoctopus/x/misc/retry"
)

func TestRetry_Do(t *testing.T) {
r := &retry.Retry{}
r.SetDefault()
g.NewWithT(t).Expect(r.Interval).To(g.Equal(retry.Default.Interval))
g.NewWithT(t).Expect(r.Repeats).To(g.Equal(retry.Default.Repeats))

times := 0
exec := func() error {
times++
if times == 3 {
return nil
}
return errors.Errorf("times %d", times)
}

g.NewWithT(t).Expect(retry.Do(r, exec)).To(g.BeNil())

times = 0
r.Repeats = 0
g.NewWithT(t).Expect(retry.Do(r, exec)).NotTo(g.BeNil())
}

0 comments on commit 0c52e6e

Please sign in to comment.