retry

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 5, 2018 License: MIT Imports: 1 Imported by: 9

README

retry

Retrying functions in Go, certain number of times or infinitely - Also can be used as a schaduler.

Documentation:

GoDoc

Get via:

$ go get -u github.com/dc0d/retry

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

func Retry(
	f func() error,
	numberOfRetries int,
	onError func(error),
	period ...time.Duration)

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

func Try(f func() error) (errRun error)

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL