Skip to content

Instantly share code, notes, and snippets.

@apotox
Last active August 8, 2023 02:02
Show Gist options
  • Save apotox/d5c2da8927ec979a4521817831effd40 to your computer and use it in GitHub Desktop.
Save apotox/d5c2da8927ec979a4521817831effd40 to your computer and use it in GitHub Desktop.
GoLang ⏱ setInterval alternative
package main
import (
"fmt"
"reflect"
"time"
)
// setInterval call p function every "interval" time
func setInterval(p interface{}, interval time.Duration) chan<- bool {
ticker := time.NewTicker(interval)
stopIt := make(chan bool)
go func() {
for {
select {
case <-stopIt:
fmt.Println("stop setInterval")
return
case <-ticker.C:
reflect.ValueOf(p).Call([]reflect.Value{})
}
}
}()
// return the bool channel to use it as a stopper
return stopIt
}
func handler() {
fmt.Printf("hello world \n")
}
func main() {
fmt.Println("go sample started")
// start the setInterval and call handler every 2 seconds
stopper := setInterval(handler, 2*time.Second)
fmt.Println("your go program ...")
// avoid the unused variable warn:
_ = stopper
// to stop setInterval uncomment the next line:
// stopper <- true
// pause the console
<-make(chan bool)
}
@apotox
Copy link
Author

apotox commented Jul 29, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment