go timer
Timer的创建
Timer是一次性的时间触发事件,这点与Ticker不同,后者则是按一定时间间隔持续触发时间事件。Timer常见的使用场景如下:
场景1:
t := time.AfterFunc(d, f)
场景2:
select {
    case m := <-c:
       handle(m)
    case <-time.After(5 * time.Minute):
       fmt.Println("timed out")
}
或:
t := time.NewTimer(5 * time.Minute)
select {
    case m := <-c:
       handle(m)
    case <-t.C:
       fmt.Println("timed out")
}Timer三种创建姿势:
t:= time.NewTimer(d)
t:= time.AfterFunc(d, f)
c:= time.After(d)time.After跟,time.AfterFunc其中第一个After接口返回一个chan Time, 当时间到时可以读出Timer, AfterFunc接受一个方法,当时间到时执行这个方法。
package main
import (
  "time"
  "fmt"
)
func main() {
  a := time.After(2 * time.Second)
  <- a
  fmt.Println("timer receive")
  time.AfterFunc(2 * time.Second, func(){
    fmt.Println("timer receive")
  })
}Timer有三个要素:
* 定时时间:也就是那个d
* 触发动作:也就是那个f
* 时间channel: 也就是t.C内部实现
由于After跟AfterFunc差不多,这里主要看看AfterFunc的实现
  //time/sleep.go
 func AfterFunc(d Duration, f func()) *Timer {
    t := &Timer{
      r: runtimeTimer{
    when: when(d),
    f:    goFunc,
    arg:  f,
      },
    }
    startTimer(&t.r)
    return t
  } 
  func goFunc(arg interface{}, seq uintptr) {
      go arg.(func())()
}AfterFunc很简单,就是把参数封装为runtimeTimer,然后启动timer(把timer添加到队列中), 这部分代码在runtime/time.go中,注意这里goFunc新启动了一个goroutine来执行用户的任务,这样用户的func就不会堵塞timer
//runtime/time.go
  func startTimer(t *timer) {
    if raceenabled {
      racerelease(unsafe.Pointer(t))
    }
    addtimer(t)
  }
  func addtimer(t *timer) {
    lock(&timers.lock)
    addtimerLocked(t)
    unlock(&timers.lock)
  }
  // Add a timer to the heap and start or kick the timer proc.
  // If the new timer is earlier than any of the others.
  // Timers are locked.
  func addtimerLocked(t *timer) {
    // when must never be negative; otherwise timerproc will overflow
    // during its delta calculation and never expire other runtime·timers.
    if t.when < 0 {
      t.when = 1<<63 - 1
    }
    //添加time到全局timer
    t.i = len(timers.t)
    timers.t = append(timers.t, t)
    //使用最小堆算法维护timer队列
    siftupTimer(t.i)
    //如果是第一个
    if t.i == 0 {
      // siftup moved to top: new earliest deadline.
      //如果在sleep中, 唤醒
      if timers.sleeping {
    timers.sleeping = false
    notewakeup(&timers.waitnote)
      }
      //如果在调度中, 等待
      if timers.rescheduling {
    timers.rescheduling = false
    goready(timers.gp, 0)
      }
    }
    //如果timer还没创建,则创建
    if !timers.created {
      timers.created = true
      go timerproc()
    }
  }
func timerproc() {
  timers.gp = getg()
  for {
    lock(&timers.lock)
    timers.sleeping = false
    now := nanotime()
    delta := int64(-1)
    for {
      if len(timers.t) == 0 {
    delta = -1
    break
      }
      t := timers.t[0]
      //得到剩余时间, 还没到时间就sleep
      delta = t.when - now
      if delta > 0 {
    break
      }
      //如果是周期性的就算下一次时间
      if t.period > 0 {
    // leave in heap but adjust next time to fire
    t.when += t.period * (1 + -delta/t.period)
    //最小堆下沉
    siftdownTimer(0)
      } else {
    // remove from heap
    //删除将要执行的timer,(最小堆算法)
    last := len(timers.t) - 1
    if last > 0 {
      timers.t[0] = timers.t[last]
      timers.t[0].i = 0
    }
    timers.t[last] = nil
    timers.t = timers.t[:last]
    if last > 0 {
      siftdownTimer(0)
    }
    t.i = -1 // mark as removed
      }
      f := t.f
      arg := t.arg
      seq := t.seq
      unlock(&timers.lock)
      if raceenabled {
    raceacquire(unsafe.Pointer(t))
      }
      //执行函数调用函数
      f(arg, seq)
      lock(&timers.lock)
    }
    //继续下一个,因为可能下一个timer也到时间了
    if delta < 0 || faketime > 0 {
      // No timers left - put goroutine to sleep.
      timers.rescheduling = true
      goparkunlock(&timers.lock, "timer goroutine (idle)", traceEvGoBlock, 1)
      continue
    }
    // At least one timer pending.  Sleep until then.
    timers.sleeping = true
    noteclear(&timers.waitnote)
    unlock(&timers.lock)
    //没到时间,睡眠delta时间
    notetsleepg(&timers.waitnote, delta)
  }
}3 其他实现方法
之前看内核的timer使用的是时间轮的方式
4 API使用
func (t *Timer) Reset(d Duration) bool
Reset使t重新开始计时,(本方法返回后再)等待时间段d过去后到期。如果调用时t还在等待中会返回真;如果t已经到期或者被停止了会返回假。
/	if !t.Stop() {
//		<-t.C
//	}
//	t.Reset(d)
//
// This should not be done concurrent to other receives from the Timer's
// channel. func (t *Timer) Stop() bool
time.Timer.C 是一个 chan time.Time 而且在 Stop 时不会关闭,所以在 <-time.Timer.C 的地方如果 Stop 了就会阻塞住。
 To ensure the channel is empty after a call to Stop, check the
// return value and drain the channel.
// For example, assuming the program has not received from t.C already:
//
//	if !t.Stop() {
//		<-t.C
//	}
//所以:
ctx, cancel := context.WithCancel(context.Background())
timer := time.NewTimer(time.Minute)
timer.Stop()
select {
    // 把上面的 cancel 保存起来可以在其它协程里中断阻塞的定时器
    case <-ctx.Done():
    // 这里会无限阻塞
    case <-timer.C:
}按照 Timer.Stop 文档 的说法,每次调用 Stop 后需要判断返回值,如果返回 false(表示 Stop 失败,Timer 已经在 Stop 前到期)则需要排掉(drain)channel 中的事件
if !t.Stop() {
	<-t.C
}但是如果之前程序已经从 channel 中接收过事件,那么上述 <-t.C 就会发生阻塞。可能的解决办法是借助 select 进行 非阻塞 排放(draining):
if !t.Stop() {
	select {
	case <-t.C: // try to drain the channel
	default:
	}
}使用 Timer 的正确方式
参考 https://github.com/golang/go/issues/11513#issuecomment-157062583 和 https://groups.google.com/g/golang-dev/c/c9UUfASVPoU/m/tlbK2BpFEwAJ ,目前 Timer 唯一合理的使用方式是:
- 程序始终在同一个 goroutine 中进行 Timer 的 Stop、Reset 和 receive/drain channel 操作
- 程序需要维护一个状态变量,用于记录它是否已经从 channel 中接收过事件,进而作为 Stop 中 draining 操作的判断依据
参考:
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号