01 介绍
timeTimerTimer02 使用方式
Timertimefunc NewTimer(d Duration) *Timer
func NewTimerTimerchannel示例代码:
func main() {
nowTime := time.Now().Unix()
fmt.Println(nowTime)
NewTimerDemo()
}
func NewTimerDemo() {
timer := time.NewTimer(2 * time.Second)
select {
case <-timer.C:
currentTime := time.Now().Unix()
fmt.Println(currentTime, "do something")
}
}
输出结果:
1665894136
1665894138 do something
2stimerselecttimer.Cfunc AfterFunc(d Duration, f func()) *Timer
func AfterFuncTimer示例代码:
func main() {
nowTime := time.Now().Unix()
fmt.Println(nowTime)
AfterFuncDemo()
}
func AfterFuncDemo() {
time.AfterFunc(2 * time.Second, func() {
currentTime := time.Now().Unix()
fmt.Println(currentTime, "do something")
})
time.Sleep(3 * time.Second)
}
time.Sleep()time.AfterFunc()03 实现原理
TimerCTimechanrruntimeTimertype Timer struct {
C <-chan Time
r runtimeTimer
}
TimerTimerCCTimerrruntimeTimertype runtimeTimer struct {
tb uintptr
i int
when int64
period int64
f func(interface{}, uintptr)
arg interface{}
seq uintptr
}
runtimeTimerwhenfarg- when:定时器执行时间。
- f:定时器执行的回调函数。
- arg:定时器执行的回调函数的参数。
Timerfunc 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
}
func NewTimerTimerTimer.rstartTimer()startTimer()when()sendTimewhen()sendTimesendTimefunc sendTime(c interface{}, seq uintptr) {
// Non-blocking send of time on c.
// Used in NewTimer, it cannot block anyway (buffer).
// Used in NewTicker, dropping sends on the floor is
// the desired behavior when the reader gets behind,
// because the sends are periodic.
select {
case c.(chan Time) <- Now():
default:
}
}
func NewTimerTimer.rstartTimer()runtimeTimerTimerTimer// startTimer adds t to the timer heap.
//go:linkname startTimer time.startTimer
func startTimer(t *timer) {
if raceenabled {
racerelease(unsafe.Pointer(t))
}
addtimer(t)
}
04 总结
timeTimerStop()Reset()