Windows WaitableTimers in C++

2

I am trying to set windows waitable timers in C++ as follows:

#define _SECOND 10000000
void Run()
{
    __int64 qwDueTime= 5 * _SECOND;

    LARGE_INTEGER   liDueTime;
    // Copy the relative time into a LARGE_INTEGER.
    liDueTime.LowPart  = (DWORD) ( qwDueTime & 0xFFFFFFFF );
    liDueTime.HighPart = (LONG)  ( qwDueTime >> 32 );

    SetWaitableTimer(
          CreateWaitableTimer(NULL,FALSE  ,L"2004"),
             &liDueTime,2000,
             (PTIMERAPCROUTINE)TimerFinished,NULL,FALSE );
    cout<<"Second"<<endl;
}

where TimerFinished is

VOID CALLBACK TimerFinished(
    LPVOID lpArg,               // Data value.
    DWORD dwTimerLowValue,      // Timer low value.
    DWORD dwTimerHighValue ) {  // Timer high value.

        cout<<"First"<<endl;
        cout.flush();
 }

But unfortunately, TimerFinished is never called..

Any help?

c++
windows
asked on Stack Overflow Jan 7, 2011 by Betamoo • edited Jan 7, 2011 by Betamoo

2 Answers

7

You could find this useful: http://msdn.microsoft.com/en-us/library/ms686289(v=vs.85).aspx

Quote:

pDueTime [in]: The time after which the state of the timer is to be set to signaled, in 100 nanosecond intervals. Use the format described by the FILETIME structure. Positive values indicate absolute time. Be sure to use a UTC-based absolute time, as the system uses UTC-based time internally. Negative values indicate relative time. The actual timer accuracy depends on the capability of your hardware. For more information about UTC-based time, see System Time.

The problem is that you should pass to SetWaitableTimer() a negative value (meaning 5 seconds from now), because positive values indicate an absolute time. It's the difference between "two days from now" (relative) and "9th of Jan" (absolute).

answered on Stack Overflow Jan 7, 2011 by Andrei Sfrent • edited Jan 7, 2011 by zdan
0

After your call to SetWaitableTimer you should put that thread (which you are calling SetWaitableTimer in) in alertable state.

To put a thread in alertable state, you need to call SleepEx(), WaitForSingleObjectEx() , WaitForMultipleObjectsEx(), MsgWaitForMultipleObjectsEx() , SignalObjectAndWait() or any other function in same group, which has bAlertable parameter set to TRUE.

Also you can see "Waitable Timers" section which is detailed here: Timers Tutorial

answered on Stack Overflow Oct 7, 2018 by tolgayilmaz

User contributions licensed under CC BY-SA 3.0