algorithmtimer

Efficient timer algorithm


What is the best algorithm to implement a simple timer library?

The library should allow the following:

  1. Timers to be started
  2. Timers to be stopped
  3. Timers to be checked whether they are still running

On timer expiry, a callback function will be called.

The timer module will allow timers to have a time resolution of Ns and the module shall be given a kick every Ns to prompt the module to check for expired timers.

Many timers may be simultaneously active.

The best algorithm needs to meet the following goals

  1. Be robust to timers being started / stopped while processing a timer expiry callback
  2. Allow timers to be started, stopped and checked quickly
  3. Have a small memory footprint

Solution

  • The best algorithm I have seen for timers is a timer wheel found in the research paper Hashed and Hierarchical Timing Wheels: Data Structures for the Efficient Implementation of a Timer Facility.

    I know in Java there is an implementation with Netty and JBoss, and I am sure elsewhere too that you can use, if you are writing in Java.