Installing a Timer

There are three tasks to perform to install a timer.

  1. Get an event loop reference.
  2. Create an event loop timer universal procedure pointer (UPP).
  3. Call the function InstallEventLoopTimer().

Most of you will be calling the function GetMainEventLoop() to get an event loop reference. As its name suggests, GetMainEventLoop() returns the main application thread’s event loop. If you create a thread for your application and want to install an event timer for that thread, call the function GetCurrentEventLoop(), which returns the current thread’s event loop.

EventLoopRef mainLoop;
mainLoop = GetMainEventLoop();

Universal procedure pointers (UPP) are a method of abstracting function pointers. What is important to know is that you have to create an event loop timer UPP to install a timer. Call the function NewEventLoopTimerUPP() to create the UPP. Supply your timer’s function name to NewEventLoopTimerUPP().

timerUPP = NewEventLoopTimerUPP(TimerFunction);

After creating the UPP you can install the timer by calling InstallEventLoopTimer(). This function takes six parameters. The first parameter is the event loop reference you got by calling GetMainEventLoop() or GetCurrentEventLoop(). The second parameter is the amount of time to wait before running the timer. If you want the timer to start firing immediately, pass the value kEventDurationNoWait. Passing the value kEventDurationForever tells the operating system to wait for you to tell it to fire the timer.

The third parameter is the timer’s firing rate. If you set a firing rate of 0, the timer fires once. The fourth parameter is the UPP you created by calling NewEventLoopTimerUPP(). The fifth parameter is a pointer to data you’re going to supply to the timer. Normally you supply a pointer to a class or data structure. The last parameter is the timer.

When you specify a firing rate or an amount of time to wait, Apple supplies constants that start with the prefix kEventDuration. You can specify firing rates and waiting times in nanoseconds, microseconds, milliseconds, seconds, minutes, hours, and days. The following example specifies a waiting time of 2 hours and a firing rate of 30 times per second:

InstallEventLoopTimer(mainLoop, (kEventDurationHour * 2),
    (kEventDurationSecond / 30),timerUPP, this, &timer);

If you want the timer to fire consistently, make sure the firing rate is slower than the time it takes for the timer to finish. If you set a firing rate of 60 times per second, but the timer takes one second to complete its tasks, the timer will end up firing approximately one time per second, not 60.

Next (Writing a Timer)
Previous (Introduction)