golang 定时器
写法一:
package mainimport ("fmt""sync""time"
)type DemoTicker struct {ch <-chan time.Timestop chan struct{}sg *sync.WaitGroup
}func main() {count, stopCount := 0, 5demo := DemoTicker{ch: time.Tick(time.Second * 1),stop: make(chan struct{}),sg: &sync.WaitGroup{},}demo.sg.Add(1)go func() {demo.sg.Done()for {select {case <-demo.ch:println("tick1")count++if count == stopCount {demo.stop <- struct{}{}}}}}()<-demo.stopdemo.sg.Wait()fmt.Println("done")}
结果:
tick1
tick1
tick1
tick1
tick1
done
写法二:
package mainimport ("fmt""sync""time"
)type DemoTicker struct {*time.Tickerstop chan struct{}sg *sync.WaitGroup
}func main() {count, stopCount := 0, 5demo := DemoTicker{Ticker: time.NewTicker(time.Second * 1),stop: make(chan struct{}),sg: &sync.WaitGroup{},}demo.sg.Add(1)ticker := demo.Tickergo func() {defer demo.sg.Done()for {select {case <-ticker.C:fmt.Printf("count:%d\n", count)count++if count == stopCount {demo.stop <- struct{}{}ticker.Stop()}}}}()<-demo.stopfmt.Printf("stop")}
结果
API server listening at: 127.0.0.1:59859
WARNING: undefined behavior - Go version go1.18.10 is too old for this version of Delve (minimum supported version 1.21)
count:0
count:1
count:2
count:3
count:4
stop
调试器 已完成,退出代码为 0