1.  timer 定时器,时间到了执行,只执行一次

package main

import (
"fmt"
"time"
) func main() {
// 1. timer基本使用
/*
timer1 := time.NewTimer(2 * time.Second)
t := time.Now()
fmt.Printf("t = %v\n", t)
t2 := <-timer1.C
fmt.Printf("t2 = %v\n", t2)
*/ // 2. 验证timer只能响应一次
/*
timer2 := time.NewTimer(time.Second)
for {
<-timer2.C // 第一次打印时间到,第二次就会死锁(原因:timer2定时器只往通道中发送一次Time数据)
fmt.Println("时间到")
}
*/ // 3. timer实现延时的功能
/*
fmt.Println("开始了", time.Now())
time.Sleep(time.Second)
fmt.Println("第一次延时:", time.Now())
timer3 := time.NewTimer(2 * time.Second)
<-timer3.C
fmt.Println("第二次延时:", time.Now())
<-time.After(3 * time.Second) // time.After() 就是对 NewTimer(d).C 的封装
fmt.Println("第三次延时:", time.Now())
*/ // 4. 停止定时器
/*
timer4 := time.NewTimer(2 * time.Second)
go func() {
<-timer4.C
fmt.Println("定时器执行了")
}()
//time.Sleep(3 * time.Second)
// 注意:如果定时器执行了,然后在调用timer4.Stop()就会返回false,如果没有执行就调用Stop()就会返回true
// 定时器一旦被关闭,从定时器通道中读取数据和后面的代码将不会在执行
b := timer4.Stop()
if b {
fmt.Println("timer4已经关闭")
}
for { }
*/ // 5. 重置定时器
fmt.Println(time.Now())
timer6 := time.NewTimer(3 * time.Second)
timer6.Reset(time.Second)
fmt.Println(<-timer6.C) }

  

2. Ticker:时间到了,多次执行

  
package main

import (
"fmt"
"sync"
"time"
) var wg sync.WaitGroup func main() {
// 2. ticker 定时器,时间到了多次执行
ticker := time.NewTicker(1 * time.Second)
wg.Add(1)
go func() {
i := 1
for {
fmt.Println(<-ticker.C)
if i == 5 {
ticker.Stop()
break
}
i++
}
wg.Done()
fmt.Println("子 goroutine结束了")
}() wg.Wait()
fmt.Println("主 goroutine 结束了...") }

  

最新文章

  1. php 画图片2
  2. 怎么在win7的64位旗舰版上配置coocs2d-x 3.2的android环境并且打包APK
  3. bootstrap-图文混排 media
  4. Android studio 启动时出现Android studio was unable to create a local connection in order
  5. 用批处理文件来手动启动和停止Oracle服务
  6. storm环境搭建
  7. 273. Integer to English Words
  8. Qt版helloworld
  9. hduAnother Graph Game
  10. ACM第六周竞赛题目——B CodeForces 478B
  11. C# 与MySQL
  12. disruptor流程
  13. 安徽省2016“京胜杯”程序设计大赛_K_纸上谈兵
  14. Video Target Tracking Based on Online Learning—深度学习在目标跟踪中的应用
  15. Linux常用命令(第二版) --文件搜索命令
  16. js相关
  17. SQL UNIQUE 约束
  18. JAVA记录-JSP页面获取服务器路径方式
  19. 音频播放封装(pcm格式,Windows平台 c++)
  20. Linux修改终端显示前缀及环境变量

热门文章

  1. c++代码编译错误查找方法之宏
  2. 【LeetCode】1162. 地图分析 As Far from Land as Possible(Python)
  3. 【LeetCode】121. Best Time to Buy and Sell Stock 解题报告(Java & Python & C++)
  4. 【LeetCode】438. Find All Anagrams in a String 解题报告(Python)
  5. JVM调参
  6. Gumbel distribution
  7. python_自动查找指定目录下的文件或目录的方法
  8. 使用springboot devtools工具实现热部署
  9. Kubernetes 部署 Kubernetes-Dashboard v2.0.0 尝鲜
  10. git 不小心把某个文件给 add 了 的解决方法