一、定时器的创建

golang中定时器有三种实现方式,分别是time.sleep、time.after、time.Timer
其中time.after和time.Timer需要对通道进行释放才能达到定时的效果

package main

import (
    "fmt"
    "time"
)

func main() {
    /*
        用sleep实现定时器
    */
    fmt.Println(time.Now())
    time.Sleep(time.Second)
    fmt.Println(time.Now())
    /*
        用timer实现定时器
    */
    timer := time.NewTimer(time.Second)
    fmt.Println(<-timer.C)
    /*
        用after实现定时器
    */
    fmt.Println(<-time.After(time.Second))

}

二、定时器的重置与停止

重置定时器 timer.Reset(d Duration)
停止定时器 timer.Stop()
三、周期定时的实现Tiker

golang中使用Tiker可以实现周期定时的效果

package main

import (
    "fmt"
    "time"
)

func main() {
    tiker := time.NewTicker(time.Second)
    for i := 0; i < 3; i++ {
        fmt.Println(<-tiker.C)
    }
}

相关文章:

  • 2021-08-02
  • 2021-09-29
  • 2022-12-23
  • 2021-08-27
  • 2021-09-10
  • 2021-07-27
  • 2021-06-27
猜你喜欢
  • 2022-12-23
  • 2021-12-15
  • 2021-12-10
  • 2022-01-23
  • 2022-01-07
相关资源
相似解决方案