time.NewTicker(x秒)定时器

定时器,每隔x秒触发一次,并发返回带有channel字段的对象。

ticker := time.NewTicker(60)即 每隔60秒执行一次

使用<-ticker.C方式进行等待阻塞,直到ticker的时间间隔到达,通道中有值才继续执行后续逻辑。

type Ticker struct {
    C <-chan Time // The channel on which the ticks are delivered.
    r runtimeTimer
}

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
}

 

posted @ 2025-08-26 20:43  使用D  阅读(16)  评论(0)    收藏  举报