go语言定时操作

ticker 

  Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals.

  这个对象以指定的时间间隔重复的向通道 C 发送时间值

   ticker := time.NewTicker(time.Millisecond * 500)
    go func() {
        for t := range ticker.C { //当管道关闭,管道内数据全部读出后,遍历会停止
            fmt.Println("Tick at", t)
        }

        /*

        for {

           t := <-ticker.C

           fmt.Println("Tick at", t)

        }

        */
    }()
    time.Sleep(time.Millisecond * 1500)
    ticker.Stop()
    fmt.Println("Ticker stopped")

    Tickers can be stopped just like timers using the Stop() method, as shown at the bottom of the example.

   

timer

    timer := time.NewTimer(time.Second)
    go func() {
        <- timer.C
        println("Timer expired")
    }()
    stop := timer.Stop()
    println("Timer cancelled:", stop)


In this case we canceled the timer before it had a chance to expire (Stop() would return false if we tried to cancel it after it expired.)



Sleep

    fmt.Println("start sleeping")

    time.Sleep(time.Second)

    fmt.Println("sleeping end")


After

tc:=time.After(time.Second) //返回一个time.C这个管道,1秒(time.Second)后会在此管道中放入一个时间点                     //(time.Now())时间点记录的是放入管道那一刻的时间值

<-tc //阻塞中,直到取出tc管道里的数据


AfterFunc

多少时间之后在goroutine line执行函数

f := func() {
    fmt.Println("Time out")
}
time.AfterFunc(1*time.Second, f)
time.Sleep(2 * time.Second) //要保证主线比子线“死的晚”,否则主线死了,子线也等于死了


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值