<a href="http://www.codeproject.com/KB/system/timers_intro.aspx#Introduction">Introduction</a>
<a href="http://www.codeproject.com/KB/system/timers_intro.aspx#Win32Timers">Standard Win32 Timers</a>
<a href="http://www.codeproject.com/KB/system/timers_intro.aspx#MMTimers">Multimedia Timers</a>
<a href="http://www.codeproject.com/KB/system/timers_intro.aspx#WaitableTimers">Waitable Timers</a>
<a href="http://www.codeproject.com/KB/system/timers_intro.aspx#QueueTimers">Queue Timers</a>
<a href="http://www.codeproject.com/KB/system/timers_intro.aspx#Conclusion">Conclusion</a>
<a></a>
The goal of this article is to show the practical use of different kinds of timers. First, we will see how to use the "standard" Win32 timers, then switch to multimedia timers, mention waitable timers and queue timers. I will try to make some general comparison between these solutions. So called high-resolution timer based on functions <code>QueryPerformanceFrequency</code> and <code>QueryPerformanceCounter</code> will not be taken into account because it can be used only to measure time intervals, and not to fire events in regular time intervals.
According to MSDN, An application uses a timer to schedule an event for a window after a specified time has elapsed. It means that if we create a timer and specify a time interval of <code>uElapse</code> milliseconds, it will do "something" every <code>uElapse</code> milliseconds, until we destroy it. It is up to us to specify what "something" is.
Timers are a useful feature offered to programmers by the OS. However, they can be easily misused: using timers for different kinds of polling (e.g. check every 200 milliseconds if the user entered some value into the edit box), is almost never a good idea. Good candidates for using timers are applications which do not depend that much on users' actions, but rather on time flow.
It is important to understand that the accuracy of timers is limited. Windows is not a real-time operating system (except Windows CE) and it is not reasonable to expect timers to handle very small time intervals (10 ms, for instance).
When the term timer is used, it is almost always referred to this kind of timer. I use the term Win32 timer in this article simply to make a distinction between them and other timers. In some texts, these timers are called user timers because they are not kernel objects, unlike waitable and queue timers.
How do Win32 timers work? First, we create a timer, specify its elapse time, and (optionally) attach it to a window. After the timer is created, it sends<code>WM_TIMER</code> messages to the window message queue, or if no window was specified, to the application queue. We can process this message to call the code that we want to be executed in regular time intervals. The timer will send <code>WM_TIMER</code> messages until it is destroyed.
To create a timer, we will use a Win32 function:

Collapse
or its MFC equivalent:

<code>hWnd</code> - The handle of the window to which the timer is associated; may be <code>NULL</code>, in which case <code>nIDEvent</code> is ignored, and the return value serves as the timer identifier.
<code>nIDEvent</code> - A nonzero timer identifier.
<code>uElapse</code> - Timer's time-out interval in milliseconds.
<code>lpTimerFunc</code> - An application-defined callback function that processes <code>WM_TIMER</code> messages. May be <code>NULL</code> (more often than not, it is).
The timer identifier. If <code>hWnd</code> is non-<code>NULL</code>, than it is equal to <code>nIDEvent</code>. In case of error, it is zero.
At some point, we will want to stop the "ticking" of the timer. We can do this by destroying it:


<code>hWnd</code> - The same value as in the call to <code>SetTimer</code>
<code></code><code>uIDEvent</code> - The timer identifier
If the function succeeds, <code>TRUE</code>; if it fails, <code>FALSE</code>
A typical use of Win32 timers from a <code>CWnd</code> - derived class looks like this:

If we need to check our Inbox for new mail every half an hour, Win32 timers are all we want. However, for more accurate time measurement (elapsed time less than 1 sec), these timers are hardly the solution. The main reason is that timer posts <code>WM_TIMER</code> messages to a message queue, and we can never be sure when this message will be processed. Now, you might think that setting <code>lpTimerFunc</code> is a solution to this problem, but that is not the case. If you specify <code>lpTimerFunc</code>, the default window procedure calls it only when it processes <code>WM_TIMER</code>. So, we will still wait for <code>WM_TIMER</code> to be processed.
Note that with a Win32 timer event processing is done from the UI thread. The nice aspect of this fact is that we don't need to worry about corrupting our data from a timer event handler; on the flip side, the time spent in a <code>WM_TIMER</code> handler will affect the responsiveness of the UI. If you don't believe me, try calling something like <code>::Sleep(10000);</code> within <code>CTimersDlg::OnTimer()</code>.
The multimedia timer is a high-resolution timer that does not post any messages to message queues. Instead, it calls the specified callback function directly on a separate thread (or, alternatively, it can set or pulse the specific event, but that option will not be covered in this article). Therefore, it is more accurate than the standard Win32 timer, but also more dangerous. Here, we do not have a message queue to protect us if we specify short elapse time.
To use multimedia timers in your projects, you should include Mmsystem.h, and link it with Winmm.lib.
The first step when using multimedia timers is setting the timer resolution. What is timer resolution? It determines the accuracy of the timer. For instance, if elapse time is 1000, and resolution is 50, multimedia timer will "tick" every 950 - 1050 milliseconds.
That sounds great. Why don't we just set the timer resolution to zero, and have an absolutely accurate timer? That's because different systems support different minimum values for the multimedia timer resolution. We can obtain this minimum value by calling:

<code>ptc</code> - Pointer to a <code>TIMECAPS</code> structure. It is filled with information about the resolution of the timer device
<code>cbtc</code> - Size of <code>TIMECAPS </code>(<code>sizeof (TIMECAPS)</code>).
<code>TIMERR_NOERROR</code> if successful or <code>TIMERR_STRUCT</code> if it fails
<code>TIMECAPS </code>is pretty simple:

<code>wPeriodMin</code> - Minimum supported resolution
<code>wPeriodMax</code> - Maximum supported resolution
We need to pick our minimum resolution to be in this range. Now, when we have it, let's set the resolution. We will do it by calling the function:

<code>uPeriod</code> - Minimum timer resolution
<code>TIMERR_NOERROR</code> if successful or <code>TIMERR_NOCANDO</code> if the resolution specified in <code>uPeriod</code> is out of range
Now that we set the resolution, let's create the timer. The multimedia timer equivalent of <code>SetTimer</code>, looks like this:

<code>uDelay</code> - Event delay, in milliseconds. Pretty much the same as <code>uElapse</code> in <code>SetTimer</code>
<code>uResolution</code> - Resolution of the timer event, in milliseconds.
<code>lpTimeProc</code> - Pointer to the callback function that we want to be called periodically
<code>dwUser</code> - User data passed to the callback function
<code>fuEvent</code> - Timer event type. May be either <code>TIME_ONESHOT</code>, in which case the callback function is called only once, or <code>TIME_PERIODIC</code> for periodic calling
An identifier for the timer event if successful or <code>NULL </code>if it fails
Let's take a look at the callback function. It is declared like this:

<code>uID</code> - Timer ID, returned by <code>timeSetEvent</code>
<code>uMsg</code> - Reserved
<code>dw1, dw2</code> - Reserved
Eventually, we will need to destroy the timer. We can accomplish this by a call to the function:

<code>uTimerID</code> - Timer ID
<code>TIMERR_NOERROR</code> if successful or <code>MMSYSERR_INVALPARAM</code> if the specified timer event does not exist
Remember setting the timer resolution? Well, after we are finished with the timer, we should "reset" the timer resolution with a call to:

<code>uPeriod</code> - The same as in <code>timeBeginPeriod</code>
<code>TIMERR_NOERROR</code> if successful or <code>TIMERR_NOCANDO</code> if fails
The multimedia timer version of the example from the previous chapter:

The example shown above is written in a way to resemble the handling of standard Win32 timers. In practice, however, I wrap the functionality of multimedia timers in a separate class, and I recommend you to do the same.
As I mentioned before, a multimedia timer runs on its own thread.
Waitable timers were introduced with Windows 98 and Windows NT 4.0. and they were designed to work with threads that need to block for some times. These timers are kernel objects which are signaled in the specified time, or in regular time intervals. They can specify the callback function (actually, an asynchronous procedure call, or APC) which gets called when timer gets signaled. This callback function is usually called a completion routine.
In order to enable execution of the completion routine, the thread must be in alertable state (executing <code>SleepEx()</code>, <code>WaitForSingleObjectEx()</code> ,<code>WaitForMultipleObjectsEx()</code>, <code>MsgWaitForMultipleObjectsEx()</code> , <code>SignalObjectAndWait()</code> functions). In practice, this means that our main thread will be blocked while we are using waitable timers.
To start working with a waitable timer, we must open an existing timer, or create the new one. Creating can be accomplished with a call to:

<code>lpTimerAttributes</code> - Pointer to a <code>SECURITY_ATTRIBUTES</code> structure that specifies a security descriptor for the waitable timer object. Can be <code>NULL</code>
<code>bManualReset</code> - Specifies whether the waitable timer is manual-reset or auto-reset
<code>lpTimerName</code> - The name of the new timer. Can be <code>NULL</code>
A handle to the waitable timer object
Another possibility is to open an existing named waitable timer.
Now, when we have a handle to the waitable timer object, we can do something useful with it. To set it, we will use the function:

<code>hTimer</code> - A handle to the timer object
<code>pDueTime</code> - Specifies when the state of the timer is to be set to signaled
<code>lPeriod</code> - The period of the timer in milliseconds, like <code>uElapse</code> in <code>SetTimer()</code>
<code>pfnCompletionRoutine</code> - The pointer to a completion routine. Can be <code>NULL</code>
<code>fResume</code> - Specifies whether to restore a system in suspended power conservation mode when the timer state is set to signaled.
Nonzero if the function succeeds
Finally, here is a function that stops the waitable timer:

<code>hTimer</code> - A handle to the <code>timer </code>object
The example will be a little different this time:

As you can see, we don't have <code>OnButtonStop()</code> now. As soon as we set the timer, we must put our calling thread into alertable state, and wait. This means that we cannot do anything in the main thread until we finish with the timer. Of course, nothing prevents us from launching a separate worker thread which won't be blocked.
What can we conclude about waitable timers? They do not spend much CPU time and they do not need a message queue. The main problem is that the thread which sets the waitable timer must put itself in an alertable state, or the completion routine will never be called.
The last kind of Windows - supported timers that we are going to read about in this article is queue timers. They were introduced with Windows 2000.
Queue timers are lightweight kernel objects that reside in timer queues. Like most timers, they enable us to specify the callback function to be called when the specified due time arrives. In this case, the operation is performed by a thread in the Windows thread pool.
Here, for the sake of simplicity, we are not going to create our timer queues. Instead, we will put our queue timers into default timer queue, provided by the OS.
First, we need to create a timer and add it to the default timer queue. For this, we'll make a call to:

<code>phNewTimer</code> - Pointer to a handle; this is an out value
<code>TimerQueue</code> - Timer queue handle. For the default timer queue, <code>NULL</code>
<code>Callback</code> - Pointer to the callback function
<code>Parameter</code> - Value passed to the callback function
<code>DueTime</code> - Time (milliseconds), before the timer is set to the signaled state for the first time
<code>Period</code> - Timer period (milliseconds). If zero, timer is signaled only once
<code>Flags</code> - One or more of the next values (table taken from MSDN):
<code>WT_EXECUTEINTIMERTHREAD</code>
The callback function is invoked by the timer thread itself. This flag should be used only for short tasks or it could affect other timer operations.
<code>WT_EXECUTEINIOTHREAD</code>
The callback function is queued to an I/O worker thread. This flag should be used if the function should be executed in a thread that waits in an alertable state.
The callback function is queued as an APC. Be sure to address reentrancy issues if the function performs an alertable wait operation.
<code>WT_EXECUTEINPERSISTENTTHREAD</code>
The callback function is queued to a thread that never terminates. This flag should be used only for short tasks or it could affect other timer operations.
Note that currently no worker thread is persistent, although no worker thread will terminate if there are any pending I/O requests.
<code>WT_EXECUTELONGFUNCTION</code>
Specifies that the callback function can perform a long wait. This flag helps the system to decide if it should create a new thread.
<code>WT_EXECUTEONLYONCE</code>
The timer will be set to the signaled state only once.
The callback function is really pretty simple:

<code>lpParameter</code> - Pointer to user-defined data
<code>TimerOrWaitFired</code> - always <code>TRUE </code>for timer callbacks
To cancel a queue timer, use the function:

<code>TimerQueue</code> - A handle to the (default) timer queue
<code>Timer</code> - A handle to the timer
<code>CompletionEvent</code> - A handle to an optional event to be signaled when the function is successful and all callback functions have completed. Can be <code>NULL</code>.
The example for queue timers is given below:

As you can see, queue timers are pretty easy to use. I can also add that they are very accurate, and "resource friendly".
As I noted at the beginning of this chapter, queue timers are supported on Windows 2000 and later. If you do not want to support older Windows versions, they are perfect, and should be used instead of multimedia timers.
What's the moral of the whole story?
When you decide that you need a timer in your application, choosing between the different timer variants should not be that hard. Follow these simple rules:
If you want your application to work on every 32 bit Windows platform, you do not need high precision, and the callback operation is fast enough not to disrupt the UI responsiveness, use a standard Win32 timer.
If you want your application to work on every 32 bit Windows platform, and you need high precision, use the multimedia timer.
If you want your application to work on Windows 98/NT4 and later, you need low system overhead, and can afford to block the calling thread, use the waitable timer.
If you want a high-precision, low-overhead, non-blocking timer that will work on Windows 2000 and later, use the queue timer.