1、超时机制Timeout
package mian func workerTimeout(start chan bool) { timeout := time.After(10 * time.Second) for { select { // … do some stuff case <- timeout: return } } } fumc main() { var intChan chan bool intChan = make(chan bool, 1) workerTimeout(intChan) }
2、心跳HeartBeart 与timeout实现类似,下面是一个简单的心跳select实现:
package mian func workerHeartbeat(start chan bool) { heartbeat := time.Tick(1 * time.Second) for { select { // … do some stuff case <- heartbeat: fmt.Println("*") //… do heartbeat stuff } } } fumc main() { var intChan chan bool intChan = make(chan bool, 1) workerHeartbeat(intChan) }
学习于:https://tonybai.com