Skip to content

Ticker

https://gobyexample-cn.github.io/tickers

go
package main

import (
	"fmt"
	"time"
)

func main() {

	ticker := time.NewTicker(500 * time.Millisecond)
	done := make(chan bool)

	go func() {
		fmt.Println("go select started")
		for {
			select {
			case <-done:
				// 没有这个 done 会卡死
				return
			case t := <-ticker.C:
				fmt.Println("Tick at", t)
			}
		}
		fmt.Println("go select stopped")
	}()

	time.Sleep(1600 * time.Millisecond)
	ticker.Stop() // Stop 并不会 close ticker.C
	done <- true
	time.Sleep(1000 * time.Millisecond)
	fmt.Println("Ticker stopped")
}