timer,只会触发一次。
<- time.NewTimer(t).C相当于time.Sleep(t)
func main() {
arr := []int{3, 1, 5, 9, 2, 8, 4, 6}
for _, d := range arr {
go p(d)
}
time.Sleep(1000 * time.Millisecond)
}
func p(d int) {
// t, _ := time.ParseDuration("0."+strconv.Itoa(d)+"s")
t:=time.Duration(d) * time.Millisecond *50
// timer := time.NewTimer(t)
// <-timer.C
<- time.NewTimer(t).C
fmt.Println(d)
}
输出:
1 2 3 4 5 6 8 9
time.NewTimer(t),时间到了只会响应一次
func main() {
t:=time.Duration(1000) * time.Millisecond
timer := time.NewTimer(t)
for{
<-timer.C //ng
// time.Sleep(t) //ok
fmt.Println(time.Now().Unix())
}
// time.Sleep(1000 * time.Millisecond)
}
输出:
1662290580
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
d:/workspace/go/demo1/a1.go:26 +0x88
exit status 2
reset可以重新设置timer的等待时间,stop可以停止timer
func main() {
timer := time.NewTimer(time.Second)
timer2 := time.NewTimer(time.Second)
go func() {
<-timer.C
fmt.Println("time1") //被停止,不打印
}()
go func() {
timer2.Reset(time.Millisecond) //马上就到时间
<-timer2.C
fmt.Println("time2")
}()
timer.Stop()
for {
}
}
ticker,每隔固定时间都会触发。
func main() {
ticker := time.NewTicker(time.Second)
t1:=time.Now().Unix()
for {
<-ticker.C
fmt.Println(time.Now().Unix())
if time.Now().Unix()-t1>3{
ticker.Stop()
break
}
}
}