Search code examples
eventsschedulerintervalsevent-drivenevent-driven-design

Time driven events architecture


I am looking into Time driven events and I can't seem to figure out how to this would be done without using an excessive amount of CPU constantly.

array events;
events[1] = [id:1,time:1440589943,event:happend];
While(running)
{
    loop over events
        if(currentTime >= eventTime)
             fireEvent()
}

This seems like the most basic event handler I can come up with but it would I think consume alot of CPU constantly without really doing anything really.

So the question basically is: How do time driven events in other any languages handle time driven events? Do they constantly check if one is ready to be fired? Do they use a clever scheduling mechanic?

Thanks in advance.


Solution

  • The common way to handle the scheduling mechanic is to place the time events on a priority queue which is typically implemented as a heap. This allows you to know when the next event is coming and sleep for an appropriate amount of time. That way you aren't continually looking for the next event and the processor can execute other meaningful work until control is passed back to handle the next scheduled event.

    Whenever a new event is registered, it is just pushed onto the priority queue. The priority queue takes care of maintaining the order of events and can store any recurring scheduling information for repeating events. In this way, an event can be processed and then added back to the queue at a future time depending on its scheduling behavior.

    The design of cron on typical unix/linux systems follows this principle. The Wikipedia article on cron contains a short overview of its implementation.