Reputation: 649
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?
Upvotes: 13
Views: 10136
Reputation: 2173
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.
Upvotes: 38