TimerTicker

Timer

内部实现源码分析

TimerTimerTimerAfterFunc
TimerNewTimerAfterFunc

类型定义如下:

type Timer struct {
    C <-chan Time     // The channel on which the time is delivered.
    r runtimeTimer
}
runtimeTimerruntimetime.gotimer
type timer struct {
    i int // heap index

    // Timer wakes up at when, and then at when+period, ... (period > 0 only)
    // each time calling f(now, arg) in the timer goroutine, so f must be
    // a well-behaved function and not block.
    when   int64
    period int64
    f      func(interface{}, uintptr)
    arg    interface{}
    seq    uintptr
}
NewTimer()
// NewTimer creates a new Timer that will send
// the current time on its channel after at least duration d.
func NewTimer(d Duration) *Timer {
    c := make(chan Time, 1)
    t := &Timer{
        C: c,
        r: runtimeTimer{
            when: when(d),
            f:    sendTime,
            arg:  c,
        },
    }
    startTimer(&t.r)
    return t
}
whenwhenruntimeNano() + int64(d)now()runtimeNano()runtimeruntime · nanotime
clock_gettimeclock_gettimegettimeofday
fsendTimeargseqf
Timerperiod
runtimetime.gosetitimertimer_createtimer_settimetimer_deleteruntimeTimerigoroutinego timerproc()runtime/time.go

Timer 相关函数或方法的使用

time.After
c := make(chan int)

go func() {
    // time.Sleep(1 * time.Second)
    time.Sleep(3 * time.Second)
    <-c
}()

select {
case c <- 1:
    fmt.Println("channel...")
case <-time.After(2 * time.Second):
    close(c)
    fmt.Println("timeout...")
}
time.Stoptime.Reset
start := time.Now()
timer := time.AfterFunc(2*time.Second, func() {
    fmt.Println("after func callback, elaspe:", time.Now().Sub(start))
})

time.Sleep(1 * time.Second)
// time.Sleep(3*time.Second)
// Reset 在 Timer 还未触发时返回 true;触发了或 Stop 了,返回 false
if timer.Reset(3 * time.Second) {
    fmt.Println("timer has not trigger!")
} else {
    fmt.Println("timer had expired or stop!")
}

time.Sleep(10 * time.Second)

// output:
// timer has not trigger!
// after func callback, elaspe: 4.00026461s
StopTimerStop
ResetstopTimerstartTimerStop

Sleep 的内部实现

runtime/time.gotimeSleepSleepTimerarggetg()

Ticker 相关函数或方法的使用

TickerTimerTickerruntimeTimerperiodNewTicker(d Duration)dd
Ticker.Stop
time.TickTicker

定时器的实际应用

TimerTikercron spec