This is a creation in Article, where the information may have evolved or changed.
Using the Golang Timer
Scheduled Tasks
func demo(input chan interface{}) { t1 := time.NewTimer(time.Second * 5) t2 := time.NewTimer(time.Second * 10) for { select { case msg <- input: println(msg) case <-t1.C: println("5s timer") t1.Reset(time.Second * 5) case <-t2.C: println("10s timer") t2.Reset(time.Second * 10) } }}
Staccato device
func main(){ ticker := time.NewTicker(time.Second) for t := range ticker.C { fmt.Println("ticker", t) }}
Timeout
func main(){ ch1 := make(chan int, 1) ch2 := make(chan int, 1) select { case e1 := <-ch1: //如果ch1通道成功读取数据,则执行该case处理语句 fmt.Printf("1th case is selected. e1=%v",e1) case e2 := <-ch2: //如果ch2通道成功读取数据,则执行该case处理语句 fmt.Printf("2th case is selected. e2=%v",e2) case <- time.After(2 * time.Second): fmt.Println("Timed out") }}
Custom Timers
func main(){ var t *time.Timer f := func(){ fmt.Printf("Expiration time : %v.\n", time.Now()) fmt.Printf("C`s len: %d\n", len(t.C)) } t = time.AfterFunc(1*time.Second, f) //让当前Goroutine 睡眠2s,确保大于内容的完整 //这样做原因是,time.AfterFunc的调用不会被阻塞。它会以一部的方式在到期事件来临执行我们自定义函数f。 time.Sleep(2 * time.Second)}
Personal blog: http://notes.xbug.site