ticker
Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals.
这个对象以指定的时间间隔重复的向通道 C 发送时间值
ticker := time.NewTicker(time.Millisecond * 500)
go func() {
for t := range ticker.C { //当管道关闭,管道内数据全部读出后,遍历会停止
fmt.Println("Tick at", t)
}
/*
for {
t := <-ticker.C
fmt.Println("Tick at", t)
}
*/
}()
time.Sleep(time.Millisecond * 1500)
ticker.Stop()
fmt.Println("Ticker stopped")
Tickers can be stopped just like timers using the Stop()
method, as shown at the bottom of the example.
timer
timer := time.NewTimer(time.Second)
go func() {
<- timer.C
println("Timer expired")
}()
stop := timer.Stop()
println("Timer cancelled:", stop)
In this case we canceled the timer before it had a chance to expire (Stop()
would return false if we tried to cancel it after it expired.)
Sleep
fmt.Println("start sleeping")
time.Sleep(time.Second)
fmt.Println("sleeping end")
After
tc:=time.After(time.Second) //返回一个time.C这个管道,1秒(time.Second)后会在此管道中放入一个时间点 //(time.Now())时间点记录的是放入管道那一刻的时间值
<-tc //阻塞中,直到取出tc管道里的数据
AfterFunc
多少时间之后在goroutine line执行函数
f := func() {
fmt.Println("Time out")
}
time.AfterFunc(1*time.Second, f)
time.Sleep(2 * time.Second) //要保证主线比子线“死的晚”,否则主线死了,子线也等于死了