Timers _ golang

We often want to execute Go code at some point in the future, or repeatedly at some interval. Go's built-in timer and ticker features make both od these easy. We'll look first at timers then tickers

package main

import (
    "fmt"
    "time"
)

func main() {

    timer1 := time.NewTimer(time.Second * 2)

    <-timer1.C
    fmt.Println("Time 1 expired")

    timer2 := time.NewTimer(time.Second)
    go func() {
        <-timer2.C
        fmt.Println("Timer 2 expired")
    }()
    stop2 := timer2.Stop()
    if stop2 {
        fmt.Println("Timer 2 stopped")
    }
}
Time 1 expired
Timer 2 stopped

总结 : 

  1 : <-timer1.C 将导致 block

  2 : If you just wanted to wait, you could have used time.Sleep; You can cancel the timer before it expires 

本文来自:博客园

感谢作者:jackkiexu

查看原文:Timers _ golang

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。