golang标准库 time

 

    Ticker
    tick在不使用时,应手动stop,否则会造成timer泄露

    func Tick(d Duration) <-chan Time
    func NewTicker(d Duration) *Ticker
    func (t *Ticker) Stop()

    for t := range time.Tick(time.Second * 2){...}

    ticker := time.NewTicker(time.Second * 2)
    for {
        select {
        case t := <-ticker.C:
            fmt.Println(t, "hello world")
        }
    }

    tick的channel的cap是1,如果发送了多次,而没来得及接收,是不是只保留第一次发送的值?

    --------------------------------------------------------------------------------
    Timer
    func After(d Duration) <-chan Time
    func NewTimer(d Duration) *Timer
    func (t *Timer) Reset(d Duration) bool
    func (t *Timer) Stop() bool


    time.After创建的timer会自动从timer堆中删除,通常直接用 <-time.After 是没问题的。但在for循环中要注意:
    for {
        select {
        case <-time.After(time.Second):        // 不好
            println("time out, and end")
        case <-ch:
        }
    }
    如果ch始终都有值,那么每次循环,time.After都会分配一个新的timer,短时间内会创建大量无用的timer。
    正确写法:
    timer := time.NewTimer(time.Second)
    for {
        timer.Reset(time.Second)
        select {
        case <-timer.C:
            println("time out, and end")
        case <-ch:
        }
    }

猜你喜欢

转载自www.cnblogs.com/ts65214/p/12976204.html