Timer usage scenarios in go language standard library

Time:2020-10-15

(1) time.NewTimer , time.NewTicker , time.Tick The use of

package main
 
import (
    "errors"
    "fmt"
    "golang.org/x/sync/errgroup"
    "time"
)
 
/**
*As long as the ticker is defined, the timer starts from this moment, and no other operation is required. It will be triggered every fixed time.
*Timer timer: the value will only be executed once after a fixed time
*If timer timer is to be executed every interval to achieve ticker effect, use func (t * timer) reset (d duration) bool
 */
func main() {
    var g errgroup.Group
 
    g.Go(func() error {
        timer := time.NewTimer(1 * time.Second)
 
        for {
            select {
            case <-timer.C:
                println("1_Tokyo_NewYork_London")
                timer.Reset(1 * time.Second)
                //To stop the timer, use the following code, which frees up resources
                // timer.Stop()
            }
            // break
        }
 
        return nil
    })
 
    g.Go(func() error {
        ticker := time.NewTicker(1 * time.Second)
 
        for {
            select {
            case <-ticker.C:
                println("2_NewYork_London_Tokyo")
                //To stop the timer, use the following code, which frees up resources
                // ticker.Stop()
            }
            // break
        }
 
        return errors.New("sgdagf")
    })
    //The function of the previous coprocessor is the same, but this time.Tick Unable to stop, that is, unable to release resources!
    g.Go(func() error {
        for {
            select {
            case <-time.Tick(1 * time.Second):
                println("3_Singapore_London_Tokyo")
            }
 
            // fmt.Println(<-time.Tick(2 * time.Second))
        }
    })
 
    if err := g.Wait(); err != nil {
        fmt.Println("Err:",err)
    } else {
        println("finish")
    }
}

(2) time.AfterFunc Use as follows:

package main
 
import "time"
 
func main() {
    f := func() { println("Tokyo_London_NewYork") }
    //After func starts a coroutine again, and the timer will only execute once when the timer reaches the fixed time!
    time.AfterFunc(2*time.Second, f)
    time.Sleep(5 * time.Second)
}

The following situation will deadlock!

package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    fmt.Println(time.Now())
    f := func() { println("Tokyo_London_NewYork") }
    //Execute the following code, deadlock will occur!
    fmt.Println(<-time.AfterFunc(2*time.Second, f).C)
}

(3) time.After Use as follows:

package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    fmt.Println("3 second before:",time.Now())
    //After function is executed only once after the fixed time! And it returns the current time after the fixed time!
    fmt.Println("3 second after:",    <-time.After(3*time.Second))
}