当前位置:网站首页>Golang standard library time

Golang standard library time

2022-06-22 03:23:00 ManNiaoQinFen

Timer

Timer seeing the name of a thing one thinks of its function , It means timer , Some timing operations can be realized , Inside is also through channel To achieve .

package main

import (
	"fmt"
	"time"
)

func main() {
    

	t1 := time.Now()
	fmt.Printf("t1: %v\n", t1)

	<-time.After(time.Second * 2) // wait for 2 Second method 1
	t2 := time.Now()
	fmt.Printf("t2: %v\n", t2)

	timer2 := time.NewTimer(time.Second * 2) // wait for 2 Second method 2
	<-timer2.C
	t3 := time.Now()
	fmt.Printf("t3: %v\n", t3)

	time.Sleep(time.Second * 2) // wait for 2 Second method 3
	t4 := time.Now()
	fmt.Printf("t4: %v\n", t4)

	timer3 := time.NewTimer(time.Second)
	go func() {
    
		<-timer3.C
		fmt.Println("Timer 3 expired")
	}()

	stop := timer3.Stop() // Stop timer 
	// prevent timer events , When the function executes ,timer The timer stops , The corresponding event is no longer executed 
	if stop {
    
		fmt.Println("Timer 3 stop")
	}

	timer4 := time.NewTimer(time.Second * 5) // Original setting 5s
	timer4.Reset(time.Second * 4)            // Reset time , Restart the clock 
	<-timer4.C
	t5 := time.Now()
	fmt.Printf("t5: %v\n", t5)

}

Ticker

Timer Only once ,Ticker Can be executed periodically .
example 1

package main

import (
	"fmt"
	"time"
)

func main() {
    
	ticker := time.NewTicker(time.Second)
	counter := 1
	for _ = range ticker.C {
    
		fmt.Println("ticker 1")
		counter++
		if counter >= 3 {
    
			ticker.Stop()
			break
		}
	}
}

Running results

ticker 1
ticker 1

example 2

package main

import (
	"fmt"
	"time"
)

func main() {
    

	chanInt := make(chan int)

	ticker := time.NewTicker(time.Second)

	go func() {
    
		for _ = range ticker.C {
    
			select {
    
			case chanInt <- 1:
			case chanInt <- 2:
			case chanInt <- 3:

			}
		}
	}()

	sum := 0
	for v := range chanInt {
    
		fmt.Printf(" receive : %v\n", v)
		sum += v
		if sum >= 10 {
    
			fmt.Printf("sum: %v\n", sum)
			break
		}
	}
}

Running results

 Receiving : 2
 receive : 1
 receive : 1
 receive : 2
 receive : 1
 receive : 2
 receive : 2
sum: 11
原网站

版权声明
本文为[ManNiaoQinFen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220308321866.html