Skip to content

Instantly share code, notes, and snippets.

@aprice
Created June 5, 2018 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aprice/811f7293298e0db4d500808c31abb0e8 to your computer and use it in GitHub Desktop.
Save aprice/811f7293298e0db4d500808c31abb0e8 to your computer and use it in GitHub Desktop.
Execute a function on a ticker.
package every
import (
"context"
"time"
)
// Every executes fn every d until ctx is canceled. Note that the first execution will not be until time.After(d).
func Every(ctx context.Context, d time.Duration, fn func()) {
t := time.NewTicker(d)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
fn()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment