package ticker import "time" type Ticker struct { C chan time.Time ticker *time.Ticker close chan struct{} } func NewTicker(d time.Duration) *Ticker { return &Ticker{ C: make(chan time.Time, 1), ticker: time.NewTicker(d), close: make(chan struct{}), } } func (t *Ticker) Start() { // 首次直接触发 t.C <- time.Now() go func() { for { select { case <-t.close: // 关闭时停止goroutine return case tc := <-t.ticker.C: // 把go原生定时器 push 的时间推送到我们定义的 time channel 中 t.C <- tc } } }() } func (t *Ticker) Reset(d time.Duration) { t.ticker.Reset(d) } func (t *Ticker) Stop() { t.ticker.Stop() close(t.close) }