Table of Contents
Introduction
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 QueryPerformanceFrequency
and QueryPerformanceCounter
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 uElapse
milliseconds, it will do "something" every uElapse
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).
Standard Win32 Timers
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 WM_TIMER
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 WM_TIMER
messages until it is destroyed.
To create a timer, we will use a Win32 function:
UINT_PTR SetTimer(HWND hWnd, UINT_PTR nIDEvent, UINT uElapse, TIMERPROC lpTimerFunc);
or its MFC equivalent:
UINT CWnd::SetTimer(UINT_PTR nIDEvent, UINT nElapse,
void (CALLBACK EXPORT* lpfnTimer)(HWND, UINT, UINT_PTR, DWORD));
Arguments
-
hWnd
-
The handle of the window to which the timer is associated; may be NULL
, in which case nIDEvent
is ignored, and the return value serves as the timer identifier.
nIDEvent
- A nonzero timer identifier.
uElapse
- Timer's time-out interval in milliseconds.
lpTimerFunc
- An application-defined callback function that processes WM_TIMER
messages. May be NULL
(more often than not, it is).
Return Value
- The timer identifier. If
hWnd
is non-NULL
, than it is equal to nIDEvent
. 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:
BOOL KillTimer(HWND hWnd, UINT_PTR uIDEvent);
or its MFC equivalent:
BOOL CWnd::KillTimer(UINT_PTR nIDEvent);
Arguments
hWnd
- The same value as in the call to SetTimer
uIDEvent
- The timer identifier
Return Value
- If the function succeeds,
TRUE
; if it fails, FALSE
A typical use of Win32 timers from a CWnd
- derived class looks like this:
void CTimersDlg::OnButtonBegin()
{
.
.
.
SetTimer (m_nTimerID, uElapse, NULL);
}
void CTimersDlg::OnButtonStop()
{
KillTimer(m_nTimerID);
}
void CTimersDlg::OnTimer(UINT nIDEvent) {
.
.
.
CDialog::OnTimer(nIDEvent);
}
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 WM_TIMER
messages to a message queue, and we can never be sure when this message will be processed. Now, you might think that setting lpTimerFunc
is a solution to this problem, but that is not the case. If you specify lpTimerFunc
, the default window procedure calls it only when it processes WM_TIMER
. So, we will still wait for WM_TIMER
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 WM_TIMER
handler will affect the responsiveness of the UI. If you don't believe me, try calling something like ::Sleep(10000);
within CTimersDlg::OnTimer()
.
Multimedia Timers
In the original version of this article, written 8 years ago, I described the multimedia timers in detail. In the meantime, they have become deprecated in favor of queue timers. If you are interested about the reasons, check out this Larry Osterman's blog post. Anyway, even at the time I originally wrote the article, the only reason to prefer multimedia timers over the queue timers was the fact that the later were introduced with Windows 2000 which was a relatively new system.
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:
MMRESULT timeGetDevCaps(LPTIMECAPS ptc, UINT cbtc);
Arguments
ptc
- Pointer to a TIMECAPS
structure. It is filled with information about the resolution of the timer device
cbtc
- Size of TIMECAPS
(sizeof (TIMECAPS)
).
Return Value
TIMERR_NOERROR
if successful or TIMERR_STRUCT
if it fails
TIMECAPS
is pretty simple:
typedef struct {
UINT wPeriodMin;
UINT wPeriodMax;
} TIMECAPS;
wPeriodMin
- Minimum supported resolution
wPeriodMax
- 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:
MMRESULT timeBeginPeriod(UINT uPeriod);
Arguments
uPeriod
- Minimum timer resolution
Return Value
TIMERR_NOERROR
if successful or TIMERR_NOCANDO
if the resolution specified in uPeriod
is out of range
Now that we set the resolution, let's create the timer. The multimedia timer equivalent of SetTimer
, looks like this:
MMRESULT timeSetEvent(UINT uDelay, UINT uResolution,
LPTIMECALLBACK lpTimeProc, DWORD dwUser, UINT fuEvent);
Arguments
uDelay
- Event delay, in milliseconds. Pretty much the same as uElapse
in SetTimer
uResolution
- Resolution of the timer event, in milliseconds.
lpTimeProc
- Pointer to the callback function that we want to be called periodically
dwUser
- User data passed to the callback function
fuEvent
- Timer event type. May be either TIME_ONESHOT
, in which case the callback function is called only once, or TIME_PERIODIC
for periodic calling
Return Value
- An identifier for the timer event if successful or
NULL
if it fails
Let's take a look at the callback function. It is declared like this:
void CALLBACK TimeProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2);
Arguments
uID
- Timer ID, returned by timeSetEvent
uMsg
- Reserved
lpTimeProc
- Pointer to the callback function that we want to be called periodically
dwUser
- User data passed to the callback function
dw1, dw2
- Reserved
Eventually, we will need to destroy the timer. We can accomplish this by a call to the function:
MMRESULT timeKillEvent(UINT uTimerID);
Argument
Return Value
TIMERR_NOERROR
if successful or MMSYSERR_INVALPARAM
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:
MMRESULT timeEndPeriod(UINT uPeriod);
Argument
uPeriod
- The same as in timeBeginPeriod
Return Value
TIMERR_NOERROR
if successful or TIMERR_NOCANDO
if fails
The multimedia timer version of the example from the previous chapter:
void CTimersDlg::OnButtonBegin()
{
.
.
.
TIMECAPS tc;
timeGetDevCaps(&tc, sizeof(TIMECAPS));
m_uResolution = min(max(tc.wPeriodMin, 0), tc.wPeriodMax);
timeBeginPeriod(resolution);
m_idEvent = timeSetEvent(
m_elTime,
resolution,
TimerFunction,
(DWORD)this,
TIME_PERIODIC);
}
void CTimersDlg::OnButtonStop()
{
timeKillEvent(m_idEvent);
timeEndPeriod (m_uResolution);
}
void CTimersDlg::MMTimerHandler(UINT nIDEvent) {
.
.
.
}
void CALLBACK TimerFunction(UINT wTimerID, UINT msg,
DWORD dwUser, DWORD dw1, DWORD dw2)
{
CTimersDlg* obj = (CTimersDlg*) dwUser;
obj->MMTimerHandler(wTimerID);
}
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
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 SleepEx()
, WaitForSingleObjectEx()
, WaitForMultipleObjectsEx()
, MsgWaitForMultipleObjectsEx()
, SignalObjectAndWait()
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:
HANDLE CreateWaitableTimer(LPSECURITY_ATTRIBUTES lpTimerAttributes,
BOOL bManualReset, LPCTSTR lpTimerName);
Arguments
lpTimerAttributes
- Pointer to a SECURITY_ATTRIBUTES
structure that specifies a security descriptor for the waitable timer object. Can be NULL
bManualReset
- Specifies whether the waitable timer is manual-reset or auto-reset
lpTimerName
- The name of the new timer. Can be NULL
Return Value
- 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:
BOOL SetWaitableTimer(HANDLE hTimer, const LARGE_INTEGER *pDueTime,
LONG lPeriod, PTIMERAPCROUTINE pfnCompletionRoutine,
LPVOID lpArgToCompletionRoutine, BOOL fResume);
Arguments
hTimer
- A handle to the timer object
pDueTime
- Specifies when the state of the timer is to be set to signaled
lPeriod
- The period of the timer in milliseconds, like uElapse
in SetTimer()
pfnCompletionRoutine
- The pointer to a completion routine. Can be NULL
fResume
- Specifies whether to restore a system in suspended power conservation mode when the timer state is set to signaled.
Return Value
- Nonzero if the function succeeds
Finally, here is a function that stops the waitable timer:
BOOL CancelWaitableTimer(HANDLE hTimer);
Argument
hTimer
- A handle to the timer
object
Return Value
- Nonzero if the function succeeds
The example will be a little different this time:
void CTimersDlg::OnButtonBegin()
{
.
.
.
timerHandle = CreateWaitableTimer(NULL, FALSE, NULL);
LARGE_INTEGER lElapse;
lElapse.QuadPart = - ((int)elapse * 10000);
BOOL succ = SetWaitableTimer(timerHandle, &lElapse, elapse, TimerProc,
this, FALSE);
for (int i = 0; i < 10; i++)
SleepEx(INFINITE, TRUE);
CancelWaitableTimer(timerHandle);
CloseHandle (timerHandle);
}
void CTimersDlg::WaitTimerHandler() {
.
.
.
}
void CALLBACK (LPVOID lpArgToCompletionRoutine,
DWORD dwTimerLowValue,
DWORD dwTimerHighValue)
{
CTimersDlg* obj = (CTimersDlg*) lpArgToCompletionRoutine;
obj->WaitTimerHandler();
}
As you can see, we don't have OnButtonStop()
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.
Queue Timers
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:
BOOL CreateTimerQueueTimer(PHANDLE phNewTimer, HANDLE TimerQueue ,
WAITORTIMERCALLBACK Callback, PVOID Parameter, DWORD DueTime,
DWORD Period, ULONG Flags);
Arguments
phNewTimer
- Pointer to a handle; this is an out value
TimerQueue
- Timer queue handle. For the default timer queue, NULL
Callback
- Pointer to the callback function
Parameter
- Value passed to the callback function
DueTime
- Time (milliseconds), before the timer is set to the signaled state for the first time
Period
- Timer period (milliseconds). If zero, timer is signaled only once
Flags
- One or more of the next values (table taken from MSDN):
WT_EXECUTEINTIMERTHREAD |
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. |
WT_EXECUTEINIOTHREAD |
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.
|
WT_EXECUTEINPERSISTENTTHREAD |
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.
|
WT_EXECUTELONGFUNCTION |
Specifies that the callback function can perform a long wait. This flag helps the system to decide if it should create a new thread. |
WT_EXECUTEONLYONCE |
The timer will be set to the signaled state only once. |
Return Value
- Nonzero if the function succeeds
The callback function is really pretty simple:
VOID CALLBACK WaitOrTimerCallback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
Arguments
lpParameter
- Pointer to user-defined data
TimerOrWaitFired
- always TRUE
for timer callbacks
To cancel a queue timer, use the function:
BOOL DeleteTimerQueueTimer(HANDLE TimerQueue, HANDLE Timer, HANDLE CompletionEvent);
Arguments
TimerQueue
- A handle to the (default) timer queue
Timer
- A handle to the timer
CompletionEvent
- A handle to an optional event to be signaled when the function is successful and all callback functions have completed. Can be NULL
.
Return Value
- Nonzero if the function succeeds
The example for queue timers is given below:
void CTimersDlg::OnButtonBegin()
{
.
.
.
BOOL success = ::CreateTimerQueueTimer(
&m_timerHandle,
NULL,
TimerProc,
this,
0,
elTime,
WT_EXECUTEINTIMERTHREAD);
}
void CTimersDlg::OnButtonStop()
{
DeleteTimerQueueTimer(NULL, m_timerHandle, NULL);
CloseHandle (m_timerHandle);
}
void CTimersDlg::QueueTimerHandler() {
.
.
.
}
void CALLBACK TimerProc(void* lpParametar,
BOOLEAN TimerOrWaitFired)
{
CTimersDlg* obj = (CTimersDlg*) lpParametar;
obj->QueueTimerHandler();
}
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.
Conclusion
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.