当前位置: 首页 > news >正文

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

http://www.xdnf.cn/news/423217.html

相关文章:

  • C语言| extern的用法作用
  • maven工程跳过@SpringTest
  • MySQL全局优化
  • 对端服务器重装系统之后远程SSH无法登录的问题
  • c 中的哈希表
  • 前端——布局方式
  • redis数据结构-10(ZREM、ZSCORE、ZINCRBY)
  • SpringSecurity当中的CSRF防范详解
  • docker(一)前言:高并发服务端技术架构的演进
  • Lighthouse Core Web Vitals 指标详解与优化指南
  • flea-cache使用之Redis哨兵模式接入
  • 推荐几个常用免费的文本转语音工具
  • PYTHON训练营DAY24
  • BGP联邦实验
  • Axure高级交互设计:文本框循环赋值实现新增、修改和查看
  • python视频拆帧并根据所选区域保存指定区域
  • Web 架构之攻击应急方案
  • workman进阶应用 GatewayWorker 仿微信 做聊天室
  • Spring WebFlux 与 WebClient 使用指南
  • Linux513 rsync本地传输 跨设备传输 一
  • 原型和原型链
  • list基础用法
  • API安全
  • 【PmHub后端篇】PmHub中基于自定义注解和AOP的服务接口鉴权与内部认证实现
  • 【fastadmin开发实战】在前端页面中使用bootstraptable以及表格中实现文件上传
  • 我的五周年创作纪念日
  • 系统稳定性之上线三板斧
  • 嵌入式开发学习日志(数据结构--顺序结构单链表)Day19
  • upload-labs通关笔记-第4关 文件上传之.htacess绕过
  • Spring Boot 应用中实现基本的 SSE 功能