golang 延时任务
通过for循环select创建一个定时任务,等待主程序往通道里写数据,并且在满足条件时及时关闭
ps:注释均可省略
package main import ( "fmt" "time" ) // 延时任务 var tFlag bool var tCh = make(chan int, 1) var count int func main() { go WaitTime() for i := 0; i < 10; i++ { if tFlag == true { break } tCh <- i //time.Sleep(1*time.Second) } fmt.Println("end") } func WaitTime() { t1 := time.NewTicker(3 * time.Second) //go func() { for { select { case <-t1.C: fmt.Println("t1定时器") //t1.Stop() tFlag = true case msg := <-tCh: fmt.Println(msg, "msg") count += msg //fmt.Println(msg) if count >= 12 { tFlag = true } } if tFlag == true { break } } //}() //fmt.Println(<-tCh,"<-tCh") //<-tCh } //0 msg //1 msg //2 msg //3 msg //4 msg //5 msg //end