package main
import (
"context"
"fmt"
"time"
)
func runPeriodic(ctx context.Context, interval time.Duration, work func()) {
t := time.NewTicker(interval)
defer t.Stop() // ALWAYS Stop the ticker
for {
select {
case <-t.C:
work()
case <-ctx.Done():
fmt.Println("stopping:", ctx.Err())
return
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
runPeriodic(ctx, 250*time.Millisecond, func() {
fmt.Println("tick", time.Now().Format(time.TimeOnly))
})
}
Create a free account and build your private vault. Share publicly whenever you want.