Go语言时间处理与定时器
1、时间处理之延迟执行
package main
import (
"fmt"
"time"
)
func main() {
timer1 :=time.NewTimer(time.Second*3)
<- timer1.C //阻塞,5秒以后继续执行
fmt.Println("wait for time1")
//以下是如果定时时间太长了,怎么终止定时
timer2 :=time.NewTimer(time.Second*10)
go func() {
<- timer2.C
fmt.Println("timer2 过期")
}()
//time.Sleep(time.Second*10)
stop2 :=timer2.Stop()//取消
if stop2{
fmt.Println("timer2终止")
}
}
2、时间处理之定时器
package main
import (
"fmt"
"time"
)
func main(){
ticker :=time.NewTicker(time.Second)//定时1秒 如果想间隔2秒执行一次只需将1改成2
go func() {
for t:=range ticker.C{ //定时干活
fmt.Println("tick",t) //干活
}
}()
time.Sleep(time.Second*10)
ticker.Stop() //结束工作
fmt.Println("game over")
}
执行结果如下:
tick 2021-03-08 17:12:12.497507 +0800 CST m=+1.000776171
tick 2021-03-08 17:12:13.501815 +0800 CST m=+2.005065678
tick 2021-03-08 17:12:14.497522 +0800 CST m=+3.000754425
tick 2021-03-08 17:12:15.497474 +0800 CST m=+4.000687587
tick 2021-03-08 17:12:16.500382 +0800 CST m=+5.003576748
tick 2021-03-08 17:12:17.499181 +0800 CST m=+6.002357865
tick 2021-03-08 17:12:18.499424 +0800 CST m=+7.002581876
tick 2021-03-08 17:12:19.501656 +0800 CST m=+8.004796119
tick 2021-03-08 17:12:20.499755 +0800 CST m=+9.002876460
game over