Home > OS >  Ticker's behavior with time.sleep()
Ticker's behavior with time.sleep()

Time:12-15

Code:

func main() {
    fmt.Println(time.Now())
    ticker := time.NewTicker(100 * time.Millisecond)
    done := make(chan bool)

    go func() {
        time.Sleep(900 * time.Millisecond)
        for {
            select {
            case <-done:
                return
            case t := <-ticker.C:
                fmt.Println("Tick at", t)
            }
        }
    }()
    time.Sleep(1600 * time.Millisecond)
    ticker.Stop()
    done <- true
    fmt.Println("Ticker stopped")
}

Output:

2021-12-15 17:00:44.2506052  0800  08 m= 0.002777301
Tick at 2021-12-15 17:00:44.3916764  0800  08 m= 0.143848501
Tick at 2021-12-15 17:00:45.2913066  0800  08 m= 1.043478701
Tick at 2021-12-15 17:00:45.4007827  0800  08 m= 1.152954801
Tick at 2021-12-15 17:00:45.4930864  0800  08 m= 1.245258501
Tick at 2021-12-15 17:00:45.6021253  0800  08 m= 1.354297401
Tick at 2021-12-15 17:00:45.6980372  0800  08 m= 1.450209301
Tick at 2021-12-15 17:00:45.7929148  0800  08 m= 1.545086901
Tick at 2021-12-15 17:00:45.901921  0800  08 m= 1.654093101
Ticker stopped

Questions: How do I interpret the result? More specifically:

  1. Why the sleep in the goroutine will pause the ticker while the sleep in the main routine will not?
  2. Is ticker.C non buffering so there aren't 16 ticks?
  3. Why the first tick has m= 0.143848501?

CodePudding user response:

  1. The sleep in the goruotine doesn't pause the ticker, it delays the moment when the value is printed for the first time.
  2. ticker.C has a buffer of 1. According to comments in code:
    // Give the channel a 1-element time buffer.
    // If the client falls behind while reading, we drop ticks
    // on the floor until the client catches up.

So there is only one buffered value there.

  1. The first tick is written into the channel roughly around the moment when the ticker duration passes for the first time ~100ms. Other ticks are then skipped because buffer in ticker.C is full and are dropped until the channel is unblocked after time.Sleep passes so we have a jump of ~900 ms.
  • Related