Use time.After: package main
import ( "log" "math/rand" "time" ) func randomSleep(min, max int64) <-chan time.Time { rand.Seed(time.Now().UnixNano()) sleepDuration := time.Duration(rand.Int63n(max-min)+min) * time.Millisecond log.Printf("Sleep duration: %v\n", sleepDuration) return time.After(sleepDuration) } func main() { select { case <-time.After(1000 * time.Millisecond): log.Println("time after chan triggered") case <-randomSleep(1000, 2000): log.Println("rand sleep triggered") } } https://play.golang.org/p/nHOPEJ8URz On Wednesday, December 28, 2016 at 2:46:03 PM UTC-5, Abhishek Singh wrote: > > Hi, > > Below is a sample example, where I'm trying to understand behaviour of > select statement. I was hoping the time.After() case clause to succeed but > observation is that either of those clauses are executed intermittently. > Would help if someone could share what's going on. > > func randomSleep(min, max int64) time.Duration { > rand.Seed(time.Now().UnixNano()) > sleepDuration := time.Duration(rand.Int63n(max-min)+min) * time.Millisecond > log.Printf("Sleep duration: %v\n", sleepDuration) > time.Sleep(sleepDuration) > return sleepDuration > } > > func main() { > sendCh := make(chan time.Duration, 1) > select { > case <-time.After(1000 * time.Millisecond): > log.Println("time after chan triggered") > case sendCh <- randomSleep(1000, 2000): > log.Println("rand sleep triggered") > } > } > > Go Playground - https://play.golang.org/p/6SosvxOUGL > > ---- > > I understand, I could workaround this behaviour via: > > func main() { > sendCh := make(chan time.Duration, 1) > go func () { sendCh <- randomSleep(1000, 2000) }() > select { > case <-time.After(1000 * time.Millisecond): > log.Println("time after chan triggered") > case <-sendCh: > log.Println("rand sleep triggered") > } > } > > Thanks. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.