欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > golang 定时器

golang 定时器

2026/2/3 5:12:21 来源:https://blog.csdn.net/lengyue1084/article/details/147919017  浏览:    关键词: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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词