1 回答

TA貢獻(xiàn)1804條經(jīng)驗 獲得超3個贊
這是 Ticker 源(請原諒行號,我從文檔源頁面復(fù)制了這個):
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.
發(fā)生了什么:
您創(chuàng)建計時器
計時器產(chǎn)生它的第一個滴答聲并緩沖它。
現(xiàn)在它等待、喚醒和阻塞,等待你消費,以便它可以產(chǎn)生第 2 個滴答。
最終,你的 goroutine 喚醒并立即消耗它產(chǎn)生的前兩個滴答聲,并再次開始產(chǎn)生滴答聲。
編輯:此外,文檔NewTicker
(這Tick
是一個方便的功能)說:
NewTicker 返回一個新的 Ticker,其中包含一個通道,該通道將以持續(xù)時間參數(shù)指定的周期發(fā)送時間。它調(diào)整間隔或丟棄滴答聲以彌補慢速接收器。持續(xù)時間 d 必須大于零;如果沒有,NewTicker 會恐慌。停止代碼以釋放相關(guān)資源。
雖然它沒有明確提到它是一個緩沖區(qū)為 1 的通道。
- 1 回答
- 0 關(guān)注
- 160 瀏覽
添加回答
舉報