Is there a way in which I can execute, for example
time.Sleep(time.Second * 5000) //basically a long period of time
and then "wake up" the sleeping goroutine when I wish to do so?
I saw that there is a Reset(d Duration)
in Sleep.go
but I'm unable to invoke it.. Any thoughts?
Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.
So no, time. Sleep does not block the goroutine. The problem is "block goroutine" is not something with a defined meaning.
The sleep function from the time package is used to pause the execution of the current thread for a particular duration of time. This can be helpful when you are performing some asynchronous activity and want to wait for a few seconds before executing some code.
There isn't a way to interrupt a time.Sleep
, however, you can make use of time.After
, and a select
statement to get the functionality you're after.
Simple example to show the basic idea:
package main
import (
"fmt"
"time"
)
func main() {
timeoutchan := make(chan bool)
go func() {
<-time.After(2 * time.Second)
timeoutchan <- true
}()
select {
case <-timeoutchan:
break
case <-time.After(10 * time.Second):
break
}
fmt.Println("Hello, playground")
}
http://play.golang.org/p/7uKfItZbKG
In this example, we're spawning a signalling goroutine to tell main to stop pausing. The main is waiting and listening on two channels, timeoutchan
(our signal) and the channel returned by time.After
. When it receives on either of these channels, it will break out of the select and continue execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With