I just started picking up Golang a couple days ago and I can't seem to figure out to break out of time.Sleep()...
I can return / break out of the for loop, but the function wont return since Sleep continues doing its thing.
I am guessing the solution is pretty simple, but I can't seem to find the answer.
func main() {
ticker := time.NewTicker(time.Second * 1)
go func() {
for i := range ticker.C {
fmt.Println("tick", i)
ticker.Stop()
break
}
}()
time.Sleep(time.Second * 10)
ticker.Stop()
fmt.Println("Hello, playground")
}
Thanks in advance!
It sounds like you want to send the main goroutine a message telling it your other goroutine is complete. For that, channels are the best way to go.
func main() {
ticker := time.NewTicker(time.Second)
done := make(chan bool, 1)
go func() {
for i := range ticker.C {
fmt.Println("tick", i)
ticker.Stop()
break
}
done <- true
}()
timer := time.NewTimer(time.Second/2)
select {
case <-done:
timer.Stop()
case <-timer.C:
ticker.Stop()
}
fmt.Println("Done")
}
Working example at http://play.golang.org/p/5NFsvC5f7P
When the timer is greater than ticker, it ticks. When it is less than, all you see is "done".
This might not be a very specific solution, but you may be able to apply it.
The way I understand it, is that you need to break out of the timer under a specific condition.
try to put a while loop around your sleep and make it sleep for a second
Set the condition as a bool on your func
while (condition_to_sleep)
{
time.Sleep(1000);
}
This way you can break out of the timer when you need to
Hope this help :)