Created
January 25, 2021 18:42
-
-
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
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 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