// Created on savesnippets.com ยท https://savesnippets.com/f5jbK9DnnAW7JI 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)) }) }