Design – Efficient Repeating Alarm Clock in Low Level Language like C

cconceptsdesignefficiency

I was thinking about it and I was curious as to how one would code an efficient repeating alarm clock in C? Would you set an alarm time and then offset the time with the ms time equivalent of a day (or two days or a week depending on how often it needed to repeat)? And then poll periodically to see if the times are equal? That sounds like a very inefficient solution, to me at least. I was am interested in how an alarm clock would work programatically.

Best Answer

There's numerous ways to acheive this, all depending on what kind of environment you're working with. Another concern is of course the latency you can afford.

If you are working on a modern operating system, you most likely have an API that will put your thread to sleep until the given time has arrived. Posix has nanosleep() and C11 has the thread_sleep() function to do this.

If you're on more primitive operating systems or programming directly for embedded hardware you may have to resort to waiting for periodic interrupts, or even using busy loops.

Update: To handle multiple alarms using the thread_sleep() approach, you could for instance store all coming alarms in a sorted list. Sleep until the first alarm triggers, do what you're supposed to and then calculate the time until the next alarm and go back to sleep. This approach uses only one timer thread, which will be very efficient as long as it satisfies your latency requirements.

Related Topic