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函数。