当前位置:网站首页>Golang timer

Golang timer

2022-04-23 19:21:00 Handsome that handsome

timer timer

  1. Used in the specified Duration After the type time, the function is called or the expression is calculated .
  2. If you just want to execute after a specified time , Use time.Sleep()
  3. Use NewTimer(), Can return Timer Type before timer expires , Cancel the timer
  4. Until you use <-timer.C Send a value , This timer will expire
 Define counters 
timer := time.NewTimer(time.Second * 2)
 Stop timer 
timer.Stop()
 Mandatory modification timer The time specified in 
timer.Reset(0) 

ticker Periodic ticker
Call a function or evaluate an expression according to a specified cycle .
You usually use go Open a new thread , Otherwise

 Define a ticker
ticker := time.NewTicker(time.Millisecond * 500)
 stop it ticker
ticker.Stop()
Ticker Trigger 
For t := range ticker.C {
    
//do something
}

demo

package main
 
import (
    "fmt"
    "time"
    "sync"
)
 
func main() {
    
    ticker := time.NewTicker(5 * time.Second)
    quit := make(chan int)
    var wg  sync.WaitGroup
 
    wg.Add(1)
    go func() {
    
        defer wg.Done()
        fmt.Println("child goroutine bootstrap start")
        for {
    
            select {
    
                case <- ticker.C:
                    fmt.Println("ticker .")
                case <- quit:
                    fmt.Println("work well .")
                    ticker.Stop()
                    return
            }
        }
        fmt.Println("child goroutine bootstrap end")
    }()
    time.Sleep(10 * time.Second)
    quit <- 1
    wg.Wait()
}

版权声明
本文为[Handsome that handsome]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210557450985.html