example_test.go 1.2 KB

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