package time提供測量和顯示時間的能力。 函數
format.go sleep.go sys_unix.go tick.go time.go zoneinfo.go zoneinfo_read.go zoneinfo_unix.go ui
1. 基本函數 google
func After(d Duration) <-chan Time在等待了d時間間隔後,向返回channel發送當前時間。與NewTimer(d).C等效。事例以下:
select { case m := <-c: handle(m) case <-time.After(5 * time.Minute): fmt.Println("timed out") }主要用於超時處理,以防死鎖。
func Sleep(d Duration)掛起當前goroutine,d時間間隔。
time.Sleep(100 * time.Millisecond)
func Tick(d Duration) <-chan TimeTick是NewTicker的一個封裝,只用於訪問ticking channel;用戶不須要關閉ticker。示例:
c := time.Tick(1 * time.Minute) for now := range c { fmt.Printf("%v %s\n", now, statusUpdate()) }2. type Duration
type Duration int64Duration是兩個納秒時間標記之間的間隔,其表示的最大間隔是290年。
const ( Nanosecond Duration = 1 Microsecond = 1000 * Nanosecond Millisecond = 1000 * Microsecond Second = 1000 * Millisecond Minute = 60 * Second Hour = 60 * Minute )上面的常量都是經常使用的duration,須要記住。
若是將一個整數轉化成一個duration的話,須要這麼作: spa
seconds := 10 fmt.Print(time.Duration(seconds)*time.Second) // prints 10s計算通過的時間間隔的示例以下,此示例很通用:
t0 := time.Now() expensiveCall() t1 := time.Now() fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
func Since(t Time) DurationSince返回從時間t開始的已流逝時間,它是time.Now().Sub(t)的濃縮版。
3. type Month .net
type Month int
const ( January Month = 1 + iota February March April May June July August September October November December )注意其寫法。
4. type Ticker unix
type Ticker struct { C <-chan Time // The channel on which the ticks are delivered. // contains filtered or unexported fields }Ticker包含一個channel,此channel以固定間隔發送ticks。
func NewTicker(d Duration) *Ticker返回一個Ticker,此Ticker包含一個channel,此channel以給定的duration發送時間。duration d必須大於0.
func (t *Ticker) Stop()用於關閉相應的Ticker,但並不關閉channel。
5. type Time 指針
type Time struct { // contains filtered or unexported fields }
Time以納秒來表示一個時刻。程序應該存儲或傳遞Time值,而不是指針,即time.Time,而非*time.Time。
6. type Timer code
type Timer struct { C <-chan Time // contains filtered or unexported fields }Timer type表明了一個事件,若是不是被AfterFunc建立的Timer,當Timer過時,當前時間將發送到C。
func AfterFunc(d Duration, f func()) *TimerAfterFunc等待duration耗盡後,在當前的goroutine中調用f函數。它返回一個Timer,利用此Timer的Stop方法,能夠取消調用f函數。