1 回答

TA貢獻1804條經驗 獲得超3個贊
這是 Ticker 源(請原諒行號,我從文檔源頁面復制了這個):
func NewTicker(d Duration) *Ticker {
if d <= 0 {
panic(errors.New("non-positive interval for NewTicker"))
}
// 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.
c := make(chan Time, 1)
t := &Ticker{
C: c,
r: runtimeTimer{
when: when(d),
period: int64(d),
f: sendTime,
arg: c,
},
}
startTimer(&t.r)
return t
}
注意評論
// 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.
發生了什么:
您創建計時器
計時器產生它的第一個滴答聲并緩沖它。
現在它等待、喚醒和阻塞,等待你消費,以便它可以產生第 2 個滴答。
最終,你的 goroutine 喚醒并立即消耗它產生的前兩個滴答聲,并再次開始產生滴答聲。
編輯:此外,文檔NewTicker
(這Tick
是一個方便的功能)說:
NewTicker 返回一個新的 Ticker,其中包含一個通道,該通道將以持續時間參數指定的周期發送時間。它調整間隔或丟棄滴答聲以彌補慢速接收器。持續時間 d 必須大于零;如果沒有,NewTicker 會恐慌。停止代碼以釋放相關資源。
雖然它沒有明確提到它是一個緩沖區為 1 的通道。
- 1 回答
- 0 關注
- 161 瀏覽
添加回答
舉報