So, I have this (just an example):
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(5 * time.Second)
for {
select {
case <-ticker.C:
fmt.Println("hello")
}
}
}
This is an infinite loop, and I want it that way. In the real code it loops every 1 hour. But, what if I want to call a func to make it stop looping? Is this possible? Something like:
func stop() {
//this will stop the main function from looping
}
I know I could do something like:
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(5 * time.Second)
done := make(chan bool)
go func() {
for {
select {
case <-done:
fmt.Println("done")
ticker.Stop()
return
case <-ticker.C:
fmt.Println("hello")
}
}
}()
time.Sleep(10 * time.Second)
done <- true
}
But that would be stoping the function from a predefined time frame(in this case 10 seconds), which is not what I want and also this is all within the same function, I need to make a call from outside the main function.
Is this possible somehow?