Documentation
¶
Overview ¶
Package retry helps retrying functions in Go, certain number of times or infinitely - Also can be used as a schaduler.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Retry ¶
Retry retries running a function, numberOfRetries times. If numberOfRetries < 0, it runs it forever as long as there are any errors. If there are no errors, it will return. If numberOfRetries > 1, it will sleep between two attemps, the default period is 5 seconds.
Example ¶
Retry(func() error {
fmt.Println(1)
return errors.Errorf("FAILED")
},
3, nil,
time.Millisecond*50)
Output: 1 1 1
Example (Error) ¶
Retry(func() error {
return errors.Errorf("FAILED")
},
3,
func(err error) { fmt.Println(err) },
time.Millisecond*50)
Output: FAILED FAILED FAILED
Example (Panic) ¶
Retry(func() error {
panic(errors.Errorf("FAILED"))
},
3, func(err error) {
e := err.(interface{ CausedBy() interface{} })
fmt.Println(e.CausedBy())
},
time.Millisecond*50)
Output: FAILED FAILED FAILED
Example (Period) ¶
startedAt := time.Now()
Retry(func() error {
return errors.Errorf("FAILED")
},
3, func(err error) { fmt.Println(time.Since(startedAt).Round(time.Millisecond * 5)) },
time.Millisecond*50)
Output: 0s 50ms 100ms
Example (Scheduler) ¶
// run every 50 millisecond, for 3 times:
var cnt int64
reschedule := errors.Errorf("re-schedule")
Retry(func() error {
atomic.AddInt64(&cnt, 1)
return reschedule
},
3, func(err error) {
if err == reschedule {
return
}
fmt.Println(err)
},
time.Millisecond*50)
fmt.Println(cnt)
Output: 3
func Try ¶
Try tries to run a function and recovers from a panic, in case one happens, and returns the error, if there are any.
Example ¶
Try(func() error {
fmt.Println("done")
return nil
})
Output: done
Example (Error) ¶
if err := Try(func() error {
return errors.New("FAILED")
}); err != nil {
fmt.Println(err)
}
Output: FAILED
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.