Last active
August 8, 2023 02:02
-
-
Save apotox/d5c2da8927ec979a4521817831effd40 to your computer and use it in GitHub Desktop.
GoLang ⏱ setInterval alternative
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 ( | |
"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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you can read more about it here https://safi-eddine-posts.herokuapp.com/2021-07-29_Go-setInterval-method-65ca8f8b69e6.html