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 

posted on 2015-03-18 13:16  xjk112  阅读(190)  评论(0编辑  收藏  举报