Skip to content

Instantly share code, notes, and snippets.

@Kugelschieber
Created January 25, 2021 18:42
Show Gist options
  • Save Kugelschieber/09e6393f1739d0394497f6630e60dd9c to your computer and use it in GitHub Desktop.
Save Kugelschieber/09e6393f1739d0394497f6630e60dd9c to your computer and use it in GitHub Desktop.
Example for running a timed function call in Golang without leaking the goroutine
package main
import (
"context"
"fmt"
"log"
"time"
)
func runTimed(tick time.Duration, f func()) context.CancelFunc {
ctx, cancelFunc := context.WithCancel(context.Background())
go func() {
timer := time.NewTimer(time.Second * 1)
defer func() {
if !timer.Stop() {
<-timer.C
}
}()
for {
timer.Reset(tick)
select {
case <-timer.C:
f()
case <-ctx.Done():
return
}
}
}()
return cancelFunc
}
func main() {
log.Println("running timed function")
cancel := runTimed(time.Second, func() {
fmt.Println("Hello, playground")
})
time.Sleep(time.Second * 5)
log.Println("stopping timer...")
cancel()
time.Sleep(time.Second * 2)
log.Println("stopped")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment