1. 程式人生 > >Go語言的定時器timer包

Go語言的定時器timer包

package main

import (
	"fmt"
	"time"
)

func main(){



	ticker:=time.NewTicker(time.Second*3)
	go func() {
		for now := range ticker.C {
			fmt.Printf("%v\n", now)
		}
	}()
	ticker.Stop()


	t2:=time.Tick(time.Second*2)
	go func() {
		for now := range t2 {
			fmt.Printf("222222222 %v\n", now)
		}
	}()

	for{
		select {
		case <-t2:
			println(11111)
		case <-time.After(time.Second*2):
			fmt.Println("timed out")
		}
	}



	timer1:=time.NewTimer(time.Second*3)
	go func() {
		for now := range timer1.C {
			fmt.Printf("%v\n", now)
		}
	}()
	time.Sleep(time.Second*7)
	timer1.Stop()

	return
	
	//使用Parse 預設獲取為UTC時區 需要獲取本地時區 所以使用ParseInLocation 獲取今天晚上23.59分59秒的時間戳
	tnow := time.Now()
	t, _ := time.ParseInLocation("2006-01-02 15:04:05", tnow.Format("2006-01-02")+" 23:59:59", time.Local)
	sub := t.Sub(tnow)       //減去當前時間 獲取現在到今晚23:59:59的時間差來建立定時器
	
	timer:=time.AfterFunc(time.Second * 2, func() {
		fmt.Println("in AfterFunc")
	})
	time.Sleep(time.Second * 3)
	timer.Reset(time.Second * 2)
	fmt.Println("Print in main")
	timer.Stop()
	time.Sleep(time.Second * 20)
}