golang timer使用

package main

import (
	"time"
	"fmt"
)

func main() {
    //创建3s的 timer
	timer := time.NewTimer(3 * time.Second)
	earliest := time.Now()
	go func() {
        //2s超时后打印时间
		select {
		case <-timer.C:
			fmt.Println("时间 ", time.Since(earliest))
			fmt.Println("Timer has expired.")
		}
	}()
    //重置为2s
	timer.Reset(2 * time.Second)
	time.Sleep(3 * time.Second)
    //since是 现在的时间到earliest的差值
	fmt.Println("时间 ", time.Since(earliest))
}

 

你可能感兴趣的:(golang开发基础)