github.com/cenkalti/backoff/v4@v4.2.1/example_test.go (about) 1 package backoff 2 3 import ( 4 "context" 5 "log" 6 ) 7 8 func ExampleRetry() { 9 // An operation that may fail. 10 operation := func() error { 11 return nil // or an error 12 } 13 14 err := Retry(operation, NewExponentialBackOff()) 15 if err != nil { 16 // Handle error. 17 return 18 } 19 20 // Operation is successful. 21 } 22 23 func ExampleRetryContext() { // nolint: govet 24 // A context 25 ctx := context.Background() 26 27 // An operation that may fail. 28 operation := func() error { 29 return nil // or an error 30 } 31 32 b := WithContext(NewExponentialBackOff(), ctx) 33 34 err := Retry(operation, b) 35 if err != nil { 36 // Handle error. 37 return 38 } 39 40 // Operation is successful. 41 } 42 43 func ExampleTicker() { 44 // An operation that may fail. 45 operation := func() error { 46 return nil // or an error 47 } 48 49 ticker := NewTicker(NewExponentialBackOff()) 50 51 var err error 52 53 // Ticks will continue to arrive when the previous operation is still running, 54 // so operations that take a while to fail could run in quick succession. 55 for range ticker.C { 56 if err = operation(); err != nil { 57 log.Println(err, "will retry...") 58 continue 59 } 60 61 ticker.Stop() 62 break 63 } 64 65 if err != nil { 66 // Operation has failed. 67 return 68 } 69 70 // Operation is successful. 71 }