Documentation
¶
Overview ¶
Package refresh allows calling a function at most once every duration. It is loosely similar to sync.Once, but with periodic refresh.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Refresher ¶
type Refresher struct {
// contains filtered or unexported fields
}
Refresher is an object that will perform an action at most once every specified duration.
func New ¶
New returns a Refresher that will call refreshFn at most once every maxAge duration. refreshFn will not be called until Load is called.
refreshFn will be called in the same goroutine as Load.
Example (Http) ¶
r := New(30*time.Minute, func() (interface{}, error) { return expensiveCall() }) r.SetStaleWhileRefresh(true) http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { data, err := r.Load() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tmpl.Execute(w, data) })
Output:
func (*Refresher) Load ¶
Load returns a value that is at most maxAge old. Load will only ever return an error that was returned from refreshFn.
The behaviour of Load when the value is stale can be controlled by SetStaleWhileRefresh. If the value is stale, it will either block all Load calls to call the refreshFn given to New, or only the first Load call.
func (*Refresher) SetStaleWhileRefresh ¶
SetStaleWhileRefresh controls the behaviour of Load when the value is stale. When set to true, only one call to Load will block while any others return stale data. When set to false, all calls to Load will block and only ever return fresh data. It defaults to false.