...
1 package backoff_test
2
3 import (
4 "context"
5 "errors"
6 "time"
7
8 backoff "github.com/lestrrat-go/backoff/v2"
9 )
10
11 func ExampleConstant() {
12 p := backoff.Constant(backoff.WithInterval(time.Second))
13
14 flakyFunc := func(a int) (int, error) {
15
16
17 switch {
18 case a%15 == 0:
19 return 0, errors.New(`invalid`)
20 case a%3 == 0 || a%5 == 0:
21 return a, nil
22 }
23 return 0, errors.New(`invalid`)
24 }
25
26 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
27 defer cancel()
28
29 retryFunc := func(v int) (int, error) {
30 b := p.Start(ctx)
31 for backoff.Continue(b) {
32 x, err := flakyFunc(v)
33 if err == nil {
34 return x, nil
35 }
36 }
37 return 0, errors.New(`failed to get value`)
38 }
39
40 retryFunc(15)
41 }
42
43 func ExampleExponential() {
44 p := backoff.Exponential(
45 backoff.WithMinInterval(time.Second),
46 backoff.WithMaxInterval(time.Minute),
47 backoff.WithJitterFactor(0.05),
48 )
49
50 flakyFunc := func(a int) (int, error) {
51
52
53 switch {
54 case a%15 == 0:
55 return 0, errors.New(`invalid`)
56 case a%3 == 0 || a%5 == 0:
57 return a, nil
58 }
59 return 0, errors.New(`invalid`)
60 }
61
62 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
63 defer cancel()
64
65 retryFunc := func(v int) (int, error) {
66 b := p.Start(ctx)
67 for backoff.Continue(b) {
68 x, err := flakyFunc(v)
69 if err == nil {
70 return x, nil
71 }
72 }
73 return 0, errors.New(`failed to get value`)
74 }
75
76 retryFunc(15)
77 }
78
View as plain text