Member-only story

Quick start: Implementing efficient and universal timer components with a minimum heap

Beck Moulton
5 min readJun 17, 2024

--

Opening

In the process of program development, timers are often used. In Linux application development, system timer resources are limited, and the number of timers that processes can create will be limited by the system. If timers are abused carelessly, it will lead to insufficient timer resources, and other modules will not be able to apply for timer resources. As mentioned above, if multiple modules in the same process need to apply for different period timers at the same time, it will cause the module to fail to create timers.

Solution

To solve the problem of timer resource shortage, there are usually the following solutions:

  • Minimum heap mode First, create a system timer and set it to trigger once. Secondly, based on the binary heap data structure, each scheduled task is arranged in the order of triggering timestamps. ③ Take the top of the stack timer task timestamp each time, calculate the trigger time, start and update the system timer trigger time. ④ After the timer is triggered, check whether the scheduled task at the top of the heap has timed out. When the timeout occurs, the corresponding event is triggered, and the timer task is removed from the top of the heap and repeated ③. (If the scheduled task is a periodic task, it will be inserted into the binary heap according to the next trigger timestamp.)
  • Time wheel mode Firstly, create a system…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet