Timers

zhaozj2021-02-17  43

Timers

You only need to know about two functions to use timers. CWnd :: SetTimer programs a timer to fire at specified intervals, and CWnd :: KillTimer stops a running timer. Depending on the parameters passed to SetTimer, a timer notifies an application that a Time Interval Has Elapsed in One of Two Ways:

By Sending a Specified WINDOW A WM_TIMER MESSAGE BY CALLING An Application-Defined Callback Function

The WM_TIMER method is the simpler of the two, but the callback method is sometimes preferable, particularly when multiple timers are used. Both types of timer notifications receive low priority when they are sent to an application. They are processed only when the message queue is DEVOID OF Other Messages.

Timer notifications are never allowed to stack up in the message queue. If you set a timer to fire every 100 milliseconds and a full second goes by while your application is busy processing other messages, it will not suddenly receive ten rapid-fire timer notifications when the message queue empties. Instead, it will receive just one. you need not worry that if you take much time to process a timer notification, another will arrive before you're finished with the previous one and start a race condition too. Still, a Windows application should never spend an excessive amount of time processing a message unless processing has been delegated to a background thread because responsiveness will suffer if the primary thread goes too long without checking the message queue.

Setting a Timer: Method 1

The easiest way to set a timer is to call SetTimer with a timer ID and a timer interval and then map WM_TIMER messages to an OnTimer function. A timer ID is a nonzero value that uniquely identifies the timer. When OnTimer is activated in response to a WM_TIMER message, the timer ID is passed as an argument. If you use only one timer, the ID value probably will not interest you because all WM_TIMER messages will originate from the same timer. An application that employs two or more timers can use the timer ID to identify the timer that generated a particular message.The timer interval passed to SetTimer specifies the desired length of time between consecutive WM_TIMER messages in thousandths of a second. Valid values ​​range from 1 through the highest number a 32-bit integer will hold : 232 - 1 MilliseConds, Which Equals Slightly More Than 491/2 Days. The Statement

Settimer (1, 500, null);

allocates a timer, assigns it an ID of 1, and programs it to send the window whose SetTimer function was called a WM_TIMER message every 500 milliseconds. The NULL third parameter configures the timer to send WM_TIMER messages rather than call a callback function. Although the programmed interval is 500 milliseconds, the window will actually receive a WM_TIMER message about once every 550 milliseconds because the hardware timer on which Windows timers are based ticks once every 54.9 milliseconds, give or take a few microseconds, on most systems (particularly Intel-based Systems). in Effect, Windows Rounds The value You Pass to settimer up to the next multiple of 55 milliseconds. thus, the statement

Settimer (1, 1, null);

Programs a Timer To send a wm_timer message Roughly Every 55 Milliseconds, as does the statement

SetTimer (1, 50, null); But change the timer interval to 60, as in

Settimer (1, 60, null);

And WM_Timer Messages Will Arrive, On Average, Every 110 MilliseConds.

How regular is the spacing between WM_TIMER messages once a timer is set The following list of elapsed times between timer messages was taken from a 32-bit Windows application that programmed a timer to fire at 500-millisecond intervals?:

Notification No.IntervalNotification No.Interval10.542 second110.604 second20.557 second120.550 second30.541 second130.549 second40.503 second140.549 second50.549 second150.550 second60.549 second160.508 second71.936 seconds170.550 second80. 261 Second180.549 Second90.550 Second190.549 Second100.549 Second200.550 SECOND

As you can see, the average elapsed time is very close to 550 milliseconds, and most of the individual elapsed times are close to 550 milliseconds, too. The only significant perturbation, the elapsed time of 1.936 seconds between the sixth and seventh WM_TIMER messages, occurred as the window was being dragged across the screen. It's obvious from this list that Windows does not allow timer messages to accumulate in the message queue. If it did, the window would have received three or four timer messages in quick succession following the 1.936-second delay.

The lesson to be learned from this is that you can not rely on timers for stopwatch-like accuracy. If you write a clock application that programs a timer for 1,000-millisecond intervals and updates the display each time a WM_TIMER message arrives, you shouldn 't assume that 60 WM_TIMER messages means that 1 minute has passed. Instead, you should check the current time whenever a message arrives and update the clock accordingly. Then if the flow of timer messages is interrupted, the clock's accuracy will be maintained.If you write an application that demands precision timing, you can use Windows multimedia timers in lieu of conventional timers and program them for intervals of 1 millisecond or less. Multimedia timers offer superior precision and are ideal for specialized applications such as MIDI sequencers, but they also Incur More Overhead and Can Adversset Running In The System.

The value returned by SetTimer is the timer ID if the function succeeded or 0 if it failed. In 16-bit versions of Windows, timers were a shared global resource and only a limited number were available. In 32-bit Windows, the number of timers the system can dole out is virtually unlimited. Failures are rare, but it's still prudent to check the return value just in case the system is critically low on resources. (Do not forget, too, that a little discretion goes a long way . An application that sets too many timers can drag down the performance of the entire system.) The timer ID returned by SetTimer equals the timer ID specified in the function's first parameter unless you specify 0, in which case SetTimer will return a timer ID of 1. SetTimer will not fail if you assign two or more timers the same ID. Rather, it will assign duplicate IDs as requested.You can also use SetTimer to change a previously assigned time-out value. If timer 1 already exists, the Statement

SetTimer (1, 1000, NULL);

Reprogram It for intervals of 1,000 milliseconds. Reprogramming a Timer Also Resets ITS INTERNAL CLOCK SO That The next NOTINALICATION WORN 'TITIL The Specified Time Period Has Elapsed.

Responding to WM_Timer Messages

MFC's on_wm_timer message-map macro Directs WM_TIMER Messages TO a Class Member Function Named Ontimer. Ontimer Is Prototyped AS Follows:

AFX_MSG Void Ontimer (uint ntimerid)

nTimerID is the ID of the timer that generated the message. You can do anything in OnTimer that you can do in other message processing functions, including grabbing a device context and painting in a window. The following code sample uses an OnTimer handler to draw ellipses Of Random Sizes And Colors in A Frame Window's Client Area. The Timer IS Programmed for 100-MilliseCond Interval in The Window's Oncreate Handler: Begin_MESSAGE_MAP (CMAINWINDOW, CFRAMEWND)

ON_WM_CREATE ()

ON_WM_TIMER ()

END_MESSAGE_MAP ()

INT CMAINWINDOW :: OnCreate (lpcreatestruct lpcs)

{

IF (cframewnd :: oncreate (lpcs) == -1)

Return -1;

IF (! settimer (id_timer_ellipse, 100, null) {

MessageBox (_T ("Error: SetTimer Failed");

Return -1;

}

Return 0;

}

Void CMainWindow :: ONTIMER (Uint Ntimerid)

{

CRECT RECT;

GetClientRect (& RECT);

INT x1 = rand ()% Rect.right;

INT x2 = rand ()% Rect.right;

INT Y1 = Rand ()% Rect.Bottom;

INT Y2 = rand ()% Rect.bottom;

CClientDC DC (this);

CBRUSH Brush (RGB (Rand ()% 255, Rand ()% 255,

RAND ()% 255));

CBRUSH * POLDBRUSH = DC.SelectObject (& brush);

Dc.ellipse (Min (x1, x2), min (Y1, Y2), Max (x1, x2),

MAX (Y1, Y2));

Dc.selectObject (Poldbrush);

}

Here's How the Same Code Fragment Wer Look if The Application Were Modified To Use Two Timers-One for Drawing Ellipses and another for Drawing Rectangles:

Begin_MESSAGE_MAP (CMainWindow, CFrameWnd)

ON_WM_CREATE ()

ON_WM_TIMER ()

END_MESSAGE_MAP ()

INT CMAINWINDOW :: OnCreate (lpcreatestruct lpcs)

{

IF (cframewnd :: oncreate (lpcs) == -1)

Return -1;

IF (! settimer (id_timer_ellipse, 100, null) ||

! SETTIMER (ID_TIMER_RECTANGLE, 100, NULL) {

MessageBox (_T ("Error: SetTimer Failed"))); Return -1;

}

Return 0;

}

Void CMainWindow :: ONTIMER (Uint Ntimerid)

{

CRECT RECT;

GetClientRect (& RECT);

INT x1 = rand ()% Rect.right;

INT x2 = rand ()% Rect.right;

INT Y1 = Rand ()% Rect.Bottom;

INT Y2 = rand ()% Rect.bottom;

CClientDC DC (this);

CBRUSH Brush (RGB (Rand ()% 255, Rand ()% 255));

CBRUSH * POLDBRUSH = DC.SelectObject (& brush);

IF (ntimerid == id_timer_ellipse)

Dc.ellipse (Min (x1, x2), min (Y1, Y2), Max (x1, x2),

MAX (Y1, Y2));

Else // ntimerid == id_timer_Rectangle

Dc.Rectangle (Min (x1, x2), min (Y1, Y2), Max (x1, x2),

MAX (Y1, Y2));

Dc.selectObject (Poldbrush);

}

As you can see, this Version of Ontimer Inspects The Ntimerid Value Passed to It to Decide WHETHER TO DRAW An Ellipse or a Rectangle.

You might not write too many applications that draw ellipses and rectangles endlessly, but using timer messages to execute a certain task or a sequence of tasks repeatedly provides an easy solution to a common problem encountered in Windows programming. Suppose you write an application with two push Button Controls Labled "Start" and "and" and "and" and "and":

m_bcontinue = true;

While (m_bcontinue)

Drawrandomellipse ();

The loop draws ellipses over and over until the Stop button is clicked, which sets m_bContinue to FALSE so that the while loop will fall through. It looks reasonable, but try it and you'll find that it does not work. Once Start is clicked, the while loop runs until the Windows session is terminated or the application is aborted with Task Manager. Why? Because the statement that sets m_bContinue to FALSE gets executed only if the WM_COMMAND message generated by the Stop button is retrieved, dispatched, and routed through the message map to the corresponding ON_COMMAND handler. But as long as the while loop is spinning in a continuous cycle without checking for messages, the WM_COMMAND message sits idly in the message queue, waiting to be retrieved. m_bContinue never changes from TRUE to FALSE , And the Program Gets Stuck in An Infinite Loop.You Solve this Problem in Several Ways. One Solution Is To Do The Drawing in a Secondary Thread So That The Primary Thread Can Continue To Pump Me ssages. Another is to add a message pump to the while loop to periodically check the message queue as ellipses are drawn. A third solution is to draw ellipses in response to WM_TIMER messages. In between WM_TIMER messages, other messages will continue to be processed as normal. The only drawback to this solution is that drawing ellipses at a rate of more than about 18 per second requires multiple timers, whereas a thread that starts drawing the next ellipse as soon as the previous one is finished might draw hundreds of ellipses per second .

An important point to take home here is that WM_TIMER messages are not processed asynchronously with respect to other messages. That is, one WM_TIMER message will never interrupt another WM_TIMER message in the same thread, nor will it interrupt a nontimer message, for that matter. WM_TIMER messages wait their turn in the message queue just as other messages do and are not processed until they are retrieved and dispatched by the message loop. If a regular message handling function and an OnTimer function use a common member variable, you can safely assume That Accesses To the Variable Won't overlap as long assetting a time window or to windows running a Timer: Method 2

Timers do not have to generate WM_TIMER messages. If you prefer, you can configure a timer to call a callback function inside your application rather than send it a WM_TIMER message. This method is often used in applications that use multiple timers so that each timer Can Be Assigned a Unique Handling Function.

A common misconception among Windows programmers is that timer callbacks are processed more expediently than timer messages because callbacks are called directly by the operating system whereas WM_TIMER messages are placed in the message queue. In reality, timer callbacks and timer messages are handled identically up to the point at which :: DispatchMessage is called. When a timer fires, Windows sets a flag in the message queue to indicate that a timer message or callback is waiting to be processed. (The on / off nature of the flag explains why timer notifications don 't stack up in the message queue. The flag is not incremented when a timer interval elapses but is merely set to "on.") If :: GetMessage finds that the message queue is empty and that no windows need repainting, it checks the timer flag. If the flag is set, :: GetMessage builds a WM_TIMER message that is subsequently dispatched by :: DispatchMessage. If the timer that generated the message is of the WM_TIMER variety, the message is dispatched to the window procedure. But if a callback function is registered instead, :: DispatchMessage calls the callback function. Therefore, callback timers enjoy virtually no performance advantage over message timers. Callbacks are subject to slightly less overhead than messages because neither a message map nor a window procedure is involved, but the difference is all but immeasurable. In practice, you'll find that WM_TIMER-type timers and callback timers work with the same regularity (or irregularity, depending on how you look at it) .To Set a Timer That Uses a callback, Specify THE Name of the callback function in the think of the callback function in the third parameter to settimer, like this:

SetTimer (ID_TIMER, 100, TIMERPROC);

The Callback Procedure, Which Is Named TimerProc in this Example, IS Prototyped As Follows: Void Callback TimerProc (HWND HWND, UINT NMSG,

Uint Ntimerid, DWORD DWTIME)

The hWnd parameter to TimerProc contains the window handle, nMsg contains the message ID WM_TIMER, nTimerID holds the timer ID, and dwTime specifies the number of milliseconds that have elapsed since Windows was started. (Some documentation says that dwTime "specifies the system time in . Coordinated Universal Time format "Do not believe it;. it's a bug in the documentation) The callback function should be a static member function or a global function to prevent a this pointer from being passed to it For more information on callback functions. And The Problems That Nonstatic MEMBER FUNCTIONS POSE for C Applications, Refer to Chapter 7.

One obstacle you'll encounter when using a static member function as a timer callback is that the timer procedure does not receive a user-defined lParam value as some Windows callback functions do When we used a static member function to field callbacks from.: :. EnumFontFamilies in Chapter 7, we passed a CMainWindow pointer in lParam to permit the callback function to access nonstatic class members in a timer procedure, you have to obtain that pointer by other means if you want to access nonstatic function and data members fortunately. You Can Get a Pointer to your application's main window with mfc's AFXGETMAINWND FUNCTION:

CMAINWINDOW * PMAINWND = (cmainwindow *) AFXGETMAINWND ();

Casting the return value to a CMainWindow pointer is necessary if you want to access CMainWindow function and data members because the pointer returned by AfxGetMainWnd is a generic CWnd pointer. Once pMainWnd is initialized in this way, a TimerProc function that is also a member of CMainWindow CAN Access Nonstatic CMainwindow Function and Data Members As IF It, TOO, WERE A NONSTICMBER FUNCTION.STOPPING A TIMER

The Counterpart To CWnd :: SetTimer Is CWnd :: KillTimer, Which Stops A Timer and Stops The Flow of WM_TIMER MESSAGER TIMER CALLBACKS. The Following Statement Releases The Timer Whose ID IS 1:

Killtimer (1);

A good place to kill a timer created in OnCreate is in the window's OnClose or OnDestroy handler. If an application fails to free a timer before it terminates, 32-bit versions of Windows will clean up after it when the process ends. Still, good Form dictates That Every Call to setTimer Should Be Paired with a call to killtimer to ensure Timer Resources Are Properly deallocated.

转载请注明原文地址:https://www.9cbs.com/read-30668.html

New Post(0)