Go标准库之time 发表于 2018-09-03 Timer 1234567891011121314//Timer类型代表一个事件。在Timer过期时,会将当前时间发送到C中。//Timer必须通过NewTimer或AfterFunc来创造type Timer struct { C <-chan Time r runtimeTimer}func (t *Timer) Reset(d Duration) bool //重置时间func (t *Timer) Stop() bool //停止执行func AfterFunc(d Duration, f func()) *Timer //延迟执行方法func After(d Duration) <-chan Time //返回延迟channel 通过NewTimer实现func NewTimer(d Duration) *Timer //返回带有延迟的Timerfunc Sleep(d Duration) 1234567891011//举例 每秒执行一次var timer *time.Timertimer=time.AfterFunc(time.Second,func(){ fmt.Println("方法执行") timer.Reset(time.Second) //闭包内使用了变量timer 注意要在闭包外显式声明})for i:=0;i<10;i++{ fmt.Println(i) time.Sleep(time.Second)} Ticker123456789//Ticker持有一个周期性“tick”的信道type Ticker struct { C <-chan Time // The channel on which the ticks are delivered. r runtimeTimer}func (t *Ticker) Stop() //关闭tickerfunc NewTicker(d Duration) *Tickerfunc Tick(d Duration) <-chan Time //返回tick channel 通过NewTicker实现 1234567ticker:=time.Tick(time.Second)for { select{ case <-ticker: fmt.Println("周期执行") }}