Created
June 5, 2018 19:41
-
-
Save aprice/811f7293298e0db4d500808c31abb0e8 to your computer and use it in GitHub Desktop.
Execute a function on a ticker.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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