* 启动时间轮 */
()
| 159 | 启动时间轮 |
| 160 | */ |
| 161 | func (tw *TimeWheel) run() { |
| 162 | for { |
| 163 | //时间轮每间隔interval一刻度时间,触发转动一次 |
| 164 | time.Sleep(time.Duration(tw.interval) * time.Millisecond) |
| 165 | |
| 166 | tw.Lock() |
| 167 | //取出挂载在当前刻度的全部定时器 |
| 168 | curTimers := tw.timerQueue[tw.curIndex] |
| 169 | //当前定时器要重新添加 所给当前刻度再重新开辟一个map Timer容器 |
| 170 | tw.timerQueue[tw.curIndex] = make(map[uint32]*Timer, tw.maxCap) |
| 171 | for tID, timer := range curTimers { |
| 172 | //这里属于时间轮自动转动,forceNext设置为true |
| 173 | tw.addTimer(tID, timer, true) |
| 174 | } |
| 175 | |
| 176 | //取出下一个刻度 挂载的全部定时器 进行重新添加 (为了安全起见,待考慮) |
| 177 | nextTimers := tw.timerQueue[(tw.curIndex+1)%tw.scales] |
| 178 | tw.timerQueue[(tw.curIndex+1)%tw.scales] = make(map[uint32]*Timer, tw.maxCap) |
| 179 | for tID, timer := range nextTimers { |
| 180 | tw.addTimer(tID, timer, true) |
| 181 | } |
| 182 | |
| 183 | //当前刻度指针 走一格 |
| 184 | tw.curIndex = (tw.curIndex + 1) % tw.scales |
| 185 | |
| 186 | tw.Unlock() |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | // Run 非阻塞的方式让时间轮转起来 |
| 191 | func (tw *TimeWheel) Run() { |