Go语言时间处理与定时器
1、时间处理之延迟执行
package main
import (
"fmt"
"time"
)
func main() {
timer1 :=time.NewTimer(time.Second*3)
<- timer1.C
fmt.Println("wait for time1")
timer2 :=time.NewTimer(time.Second*10)
go func() {
<- timer2.C
fmt.Println("timer2 过期")
}()
stop2 :=timer2.Stop()
if stop2{
fmt.Println("timer2终止")
}
}
2、时间处理之定时器
package main
import (
"fmt"
"time"
)
func main(){
ticker :=time.NewTicker(time.Second)
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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步