There are two common ways to implement timers:
- The minimum heap
- Time round
Minimum heap of insert time complexity is O (logn), such as ScheduledThreadPoolExecutor DelayedWorkQueue, and the realization of the wheel of time, insert needs only O (1), in the deleted due time complexity is O (1)
Time wheel is divided into a single layer and multi-layer, multi-layer mainly to solve the problem of time overflow, can also use the realization of a single wheel multi-ring, here with golang wrote a single wheel multi-ring implementation, test code…
A time wheel with a minimum time scale of 100ms and 1024 slots is generated, tw.AddScheduleTask means to add a scheduled task, and the test result is:
Nothing else… Specific look at the source code and test code…
Source address: Github