Timers Tutorial

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 sendsWM_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:

 Collapse

UINT_PTR SetTimer(HWND hWnd, UINT_PTR nIDEvent, UINT uElapse, TIMERPROC lpTimerFunc);

or its MFC equivalent:

 Collapse

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:

 Collapse

BOOL KillTimer(HWND hWnd, UINT_PTR uIDEvent);

or its MFC equivalent:

 Collapse

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:

 Collapse

void CTimersDlg::OnButtonBegin()
{
	.
	.
	.
    // create the timer

    SetTimer (m_nTimerID, uElapse, NULL);
}

void CTimersDlg::OnButtonStop()
{
    // destroy the timer
    KillTimer(m_nTimerID);
}

void CTimersDlg::OnTimer(UINT nIDEvent)  // called every uElapse milliseconds
{
	// do something, but quickly
	.
	.
	.

	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:

 Collapse

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:

 Collapse

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:

 Collapse

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:

 Collapse

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:

 Collapse

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:

 Collapse

MMRESULT timeKillEvent(UINT uTimerID);

Argument

  • uTimerID - Timer ID

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:

 Collapse

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:

 Collapse

void CTimersDlg::OnButtonBegin()
{
	.
	.
	.
    // Set resolution to the minimum supported by the system

    TIMECAPS tc;
    timeGetDevCaps(&tc, sizeof(TIMECAPS));
    m_uResolution = min(max(tc.wPeriodMin, 0), tc.wPeriodMax);
    timeBeginPeriod(resolution);

    // create the timer

    m_idEvent = timeSetEvent(
        m_elTime,
        resolution,
        TimerFunction,
        (DWORD)this,
        TIME_PERIODIC);
}

void CTimersDlg::OnButtonStop()
{
    // destroy the timer
    timeKillEvent(m_idEvent);

    // reset the timer
    timeEndPeriod (m_uResolution);
}

void CTimersDlg::MMTimerHandler(UINT nIDEvent) // called every elTime milliseconds
{
// do what you want to do, but quickly
	.
	.
	.
}

void CALLBACK TimerFunction(UINT wTimerID, UINT msg,
    DWORD dwUser, DWORD dw1, DWORD dw2)
    {
    // This is used only to call MMTimerHandler

    // Typically, this function is static member of CTimersDlg

    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:

 Collapse

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:

 Collapse

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:

 Collapse

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:

 Collapse

void CTimersDlg::OnButtonBegin()
{
	.
	.
	.
    // create the timer

    timerHandle = CreateWaitableTimer(NULL, FALSE, NULL);
    // set the timer

	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() // called every elTime milliseconds
{
// do what you want to do, but quickly
	.
	.
	.
}

void CALLBACK (LPVOID lpArgToCompletionRoutine,
                                DWORD dwTimerLowValue,
                                DWORD dwTimerHighValue)
    {
    // This is used only to call WaitTimerHandler
    // Typically, this function is static member of CTimersDlg
    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:

 Collapse

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:

 Collapse

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:

 Collapse

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:

 Collapse

void CTimersDlg::OnButtonBegin()
{
	.
	.
	.
    // create the timer

	BOOL success = ::CreateTimerQueueTimer(
		&m_timerHandle,
		NULL,
		TimerProc,
		this,
		0,
		elTime,
		WT_EXECUTEINTIMERTHREAD);
}

void CTimersDlg::OnButtonStop()
{
    // destroy the timer
	DeleteTimerQueueTimer(NULL, m_timerHandle, NULL);
	CloseHandle (m_timerHandle);
}

void CTimersDlg::QueueTimerHandler() // called every elTime milliseconds
{
// do what you want to do, but quickly
	.
	.
	.
}

void CALLBACK TimerProc(void* lpParametar,
                                    BOOLEAN TimerOrWaitFired)
    {
    // This is used only to call QueueTimerHandler
    // Typically, this function is static member of CTimersDlg
    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:

  1. 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.
  2. If you want your application to work on every 32 bit Windows platform, and you need high precision, use the multimedia timer.
  3. 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.
  4. If you want a high-precision, low-overhead, non-blocking timer that will work on Windows 2000 and later, use the queue timer.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

时间: 2025-01-29 22:00:46

Timers Tutorial的相关文章

Tutorial for migrating data from MS Access to MySQL(英文的哦,要有思想准备)

access|mysql Tutorial for migrating data from MS Access to MySQL One of the main reasons I started FreeSQL.org is to open up newbie users to the wide world of enterprise-level database access. One of the most common questions I'm asked is "how do I u

J2ME MIDP Currency Converter Tutorial for NetBeans IDE 4.0

j2me MIDP Currency Converter Tutorial for NetBeans IDE 4.0Feedback http://www.netbeans.org/kb/articles/tutorial-currencyconverter-40.html Feedback The Currency Converter application you will build in this tutorial shows you how to: start a j2me MIDP

F# Tutorial

// F# Tutorial File // // This file contains sample code to guide you through the // primitives of the F# language. // // Learn more about F# at http://fsharp.net // // For a larger collection of F# samples, see: // http://go.microsoft.com/fwlink/?Li

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十五)

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十五)制作精美的可任意拖放对象的物品栏及装备栏 在通常的网络游戏中,物品.装备.技能.快捷按钮等窗口中的图标都是可以相互拖放的,不同的栏目有着不同的限制,例如技能图标不能拖放到物品栏及装备栏中,且不是所有的魔法技能都可以拖放(如被动技能等):而非装备类的所有物品则无法拖放到角色的装备栏中.那么本节我将向大家讲解如何在本教程示例游戏中添加物品栏及装备栏,并实现它们之间双向物品交换的两种模式:拖放模式和双击模

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十四)

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十四)制作主角属性面板及加点器 游戏中会使用大量的菜单面板,而这些面板往往都带有选项卡.如果用Silverlight工具中的TabControl,则需要通过复杂的xaml重写模板来实现自定义样式,这一点时常让开发者头疼,毕竟界面的东西应该属于美工的范畴,这也是我所发现在目前Silverlight中唯一一处只能通过xaml而无法用代码实现的地方.当然,如果您对此特别感兴趣,同样可以到http://www.c

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十三)

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十三)制作游戏主菜单面板及鼠标左右键快捷技能栏 每款MMORPG都有一个主菜单,通常置于窗口的底部.游戏中主角大部分的设置操作都从这里开启.如人物属性.物品(包裹).技能.任务.队伍.地图.家族.门派.商城.系统设置等等:当然,还包括快捷自定义菜单栏,以及类似<暗黑破坏神>中经典式的左右键快捷技能栏.这些内容在不同的游戏中往往会根据自身的特性稍做调整,但整体上大同小异.本节,我将同样以<剑侠世界&

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十二)

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十二)制作精美的Mini地图② 前面章节中讲解的包括对象头像面板.Mini雷达地图等窗体都是位置固定的,在处理起来方式多样且简单:而RPG.SLG.休闲养成等类型的游戏中往往会大量使用到悬浮且可自由拖动的窗体,比如包裹面板.武器装备面板.个人属性面板.技能面板.系统设置面板等等,这就要求我们必须为游戏量身定做一个通用且易用的ChildWindow控件.那么本节我将为大家讲解如何制作一个包含可拖动头部.关闭

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十一)

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十一)制作精美的Mini地图① 用什么来承受未来几个月日思夜想的折磨?除了学习还是学习. 感慨了一翻,嘿嘿.本节我将为大家讲解如何为Silverlight游戏制作一个精美的Mini地图.Mini地图又分两种,一种是通常处于游戏窗口右上角的Mini雷达(导航)地图:另一种是全景Mini寻路地图.本节我先向大家讲解如何制作导航Mini雷达地图.此类地图在游戏中主要起到导航作用,即引导主角前行的方向,并且呈现出

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十)

C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(四十)向Silverlight移植② 三.新增功能: 1)新增游戏的音乐及音效对象: public static MediaElement gameMusic, gameAudio; 2)新增游戏鼠标光标: //设置游戏鼠标光标 GameCursor.Stretch = Stretch.Fill; GameCursor.Source = Super.GetImage("/Image/Cursor/0.png