A: The Timer

1.Timer Timer framework implementation

package main

import (
    "fmt"
    "time"
)

func main (a) {
    d := time.Duration(time.Second * 2)
    t := time.NewTimer(d)
    go func(a) {
        for {
            <- t.C
            fmt.Println("Timer task is working")
            t.Reset(time.Second * 2)}} ()for {
        fmt.Println("main is running:")
        time.Sleep(time.Duration(1 * time.Second))
    }
    defer t.Stop()
}
Copy the code

Ticker timer

1.Ticker timer framework implementation

package main

import (
    "fmt"
    "time"
)

func main (a) {
    d := time.Duration(time.Second * 2)
    t := time.NewTicker(d)
    go func(a) {
        for {
            <- t.C
            fmt.Println("Timer task is working")}} ()for {
        fmt.Println("main is running:")
        time.Sleep(time.Duration(1 * time.Second))
    }
    defer t.Stop()
}

Copy the code

3. Differences between Timer and Ticker

1. The Ticker does not need to Reset after the Timer expires. The Ticker performs the task processing function every time the Timer expires

// If the Timer does not use Reset, only one task is executed
package main

import (
    "fmt"
    "time"
)

func main (a) {
    d := time.Duration(time.Second * 2)
    t := time.NewTimer(d)
    go func(a) {
        for {
            <- t.C
            fmt.Println("Timer task is working")
            //t.Reset(time.Second * 2)
        }
    }()
    for {
        fmt.Println("main is running:")
        time.Sleep(time.Duration(1 * time.Second))
    }
    defer t.Stop()
}
Copy the code

Iv. Reference materials

My.oschina.net/renhc/blog/… Blog.csdn.net/lanyang1234… Draveness. Me/golang/docs…