I do this on embedded systems (pure c), where I cannot write a lot of resources (for example, 4k RAM is system memory). This is one approach that has been used (successfully):
- Create a single system timer (interrupt) that turns off periodically (for example, every 10 ms).
- A “timer” is an entry in the dynamic list that indicates how many “ticks” remain before the timer.
- Each time the system timer goes off, iterate over the list and decrease each of the "timers". Everyone that is zero is "fired." Remove it from the list and do whatever the timer should have done.
What happens when the timer goes off depends on the application. This can be started by the state machine. This may be a function call. This may be an enumeration in which the execution code is indicated, what to do with the parameter that sent him the "Create a timer" call. The information in the timer structure is what is needed in the design context. "Number of ticks" is a secret sauce.
We also created this by returning an "identifier" for the timer (usually this is the address of the timer structure that is retrieved from the pool), so it can be canceled or the status on it can be obtained.
Convenience features convert seconds to ticks, so the timer creation API is always in terms of seconds or milliseconds.
You set the tick interval to a reasonable value to compromise detail.
I made other implementations of this in C ++, C #, objective-C, with a slight change in the general approach. This is a very general design / architecture of timer subsystems. You just need something to create a fundamental “tick”.
I even did it once with a tough "main" cycle and a stopwatch from a high-precision internal timer to create my own "simulated" tick when I did not have a timer. I do not recommend this approach; I simulated hardware in a direct console application and did not have access to system timers, so this was a bit of an extreme case.
Iterating over a list of hundreds of timers 10 times per second is not such a big deal on a modern processor. You can also overcome this by inserting items with "delta seconds" and placing them in a list in sorted order. Therefore, you should check only those listed at the top of the list. This will allow you to solve scaling problems, at least in terms of list repetition.
Was this helpful?
FuzzyBunnySlippers
source share