Go Time 时间

发布时间: 更新时间: 总字数:321 阅读时间:1m 作者: IP上海 分享 网址

Time 时间lib

介绍

  • time 用来处理时间
    • time/rate 实现了一个速率限制器功能
    • $GOROOT/lib/time/zoneinfo.zip 有定义 time 的时区

示例

package main

import (
	"fmt"
	"time"
)

func main() {
	seconds := 10
	fmt.Print(time.Duration(seconds) * time.Second) // prints 10s
	fmt.Println()
	hours, _ := time.ParseDuration("10h")
	fmt.Printf("%v %#v %T\n", hours, hours, hours)

	// 每个3秒执行
	ticker := time.NewTicker(time.Second * 3)
	for {
		fmt.Println("hit")
		<-ticker.C
	}
}

time.NewTimer 定时器

package main

import (
	"fmt"
	"time"
)

func main() {

	// Timers represent a single event in the future. You
	// tell the timer how long you want to wait, and it
	// provides a channel that will be notified at that
	// time. This timer will wait 2 seconds.
	timer1 := time.NewTimer(2 * time.Second)

	// The `<-timer1.C` blocks on the timer's channel `C`
	// until it sends a value indicating that the timer
	// fired.
	<-timer1.C
	fmt.Println("Timer 1 fired")
}

time.NewTicker 定时器

package main

import (
	"fmt"
	"time"
)

func main() {
	timer := time.NewTimer(10 * time.Second)

	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()
	for {
		select {
		case <-timer.C:
			fmt.Println("Done")
			return
		case t := <-ticker.C:
			fmt.Println("ticker at: ", t)
		}
	}
}
  • 注意
    • for + select + time.After 会导致内存泄露。因为在 for 循环每次进行 select 时,都会重新初始化一个全新的计时器(Timer),示例
  # 错误的示例
  for {
      select {
      ...
      case <-time.After(1 * time.Minute):
          fmt.Printf("%d", time.Now().Unix())
      }
  }

  # 正确的示例
  timer := time.NewTimer(1 * time.Minute)
  defer timer.Stop()
  for {
      select {
      case <- timer.C:
          fmt.Printf("%d", time.Now().Unix())
      }
  }
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数