gofunc() { for t := range ticker.C { log.Printf("Tick at %v\n", t.UTC()) } }()
time.Sleep(5 * time.Second) }
输出:
1 2 3 4
2024/04/10 15:15:03 Tick at 2024-04-10 07:15:03.9905864 +0000 UTC 2024/04/10 15:15:04 Tick at 2024-04-10 07:15:04.9827231 +0000 UTC 2024/04/10 15:15:05 Tick at 2024-04-10 07:15:05.989957 +0000 UTC 2024/04/10 15:15:06 Tick at 2024-04-10 07:15:06.980916 +0000 UTC
立即执行,不用等待第一次间隔
上一个示例中如果我们在 main() 函数内第一行加上 fmt.Println("Starting ticker: ", time.Now().UTC()),查看终端输出会发现实际上是间隔了我们设定的间隔值才输出定时器发送的时间值。如果我们需要在 for 中立即拿到定时器发送的时间,可以这样子来实现:
gofunc() { for ; ; <-ticker.C { log.Printf("Tick at %v\n", time.Now().UTC()) } }()
time.Sleep(5 * time.Second) }
输出:
1 2 3 4 5 6
Starting ticker: 2024-04-10 07:57:05.6394014 +0000 UTC 2024/04/10 15:57:05 Tick at 2024-04-10 07:57:05.6394014 +0000 UTC 2024/04/10 15:57:06 Tick at 2024-04-10 07:57:06.6450901 +0000 UTC 2024/04/10 15:57:07 Tick at 2024-04-10 07:57:07.6513953 +0000 UTC 2024/04/10 15:57:08 Tick at 2024-04-10 07:57:08.6409958 +0000 UTC 2024/04/10 15:57:09 Tick at 2024-04-10 07:57:09.6480314 +0000 UTC
上面的代码中我们注意到 for ; ; <-ticker.C 这里我们并没有读取定时器发送过来的时间,并且日志输出的时间是使用的 time.Now().UTC(),这种方式并不是很好的实践,还可能存在意想不到的副作用,所以改成下面这种方式才是最佳实践:
1 2 3
for t := time.Now(); ; t = <-ticker.C { log.Printf("Tick at: %v\n", t.UTC()) }
gofunc() { for { select { case <-done: return case t := <-ticker.C: fmt.Println("Tick at", t.UTC()) } } }() time.Sleep(5 * time.Second) ticker.Stop() done <- true fmt.Println("Ticker stopped") }
输出:
1 2 3 4 5 6
Tick at 2024-04-1008:53:42.403751 +0000 UTC Tick at 2024-04-1008:53:43.3943259 +0000 UTC Tick at 2024-04-1008:53:44.4026484 +0000 UTC Tick at 2024-04-1008:53:45.3922398 +0000 UTC Tick at 2024-04-1008:53:46.400103 +0000 UTC Ticker stopped
for passengerId := 0; ; passengerId++ { select { case <-done: fmt.Println("座位满了") return case <-ticker.C: fmt.Println("时间到了,开始发车,总人数:", bus.cap) return default: time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond) passenger := Passenger{id: passengerId} go bus.AddPassenger(passenger) } } }
// 删除切片中的元素 funcDeleteSlice(s []Passenger, elem Passenger) []Passenger { r := s[:0] for _, v := range s { if v != elem { r = append(r, v) } } return r }