-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(misc/retry): add execution retrier
- Loading branch information
Showing
2 changed files
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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) | ||
} |
This file contains 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
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()) | ||
} |