ticker := time.NewTicker(updateInterval) defer ticker.Stop() ... select { case u:= <-ch1: ... case v:= <-ch2: ... case <-ticker.C: logState(status) // call some logging function logState default: // no value ready to be received ... }
import"time" rate_per_sec := 10 var dur Duration = 1e9 / rate_per_sec chRate := time.Tick(dur) // a tick every 1/10th of a second for req := range requests { <- chRate // rate limit our Service.Method RPC calls go client.Call("Service.Method", req, ...) }
定时器(Timer)定时器和计时器(Ticker)结构体类似(构造函数为 NewTimer(d Duration)),但它只发送一次时间,在 Dration d 之后。
timeout := make(chanbool, 1) gofunc() { time.Sleep(1e9) // one second timeout <- true }() select { case <-ch: // a read from ch has occured case <-timeout: // the read from ch has timed out break }
// acquire n resources func (s semaphore) P(n int) { e := new(Empty) for i := 0; i < n; i++ { s <- e } } // release n resouces func (s semaphore) V(n int) { for i:= 0; i < n; i++{ <- s } }