Betamoo
Betamoo

Reputation: 15900

Windows WaitableTimers in C++

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?

Upvotes: 2

Views: 7076

Answers (2)

tolgayilmaz
tolgayilmaz

Reputation: 4185

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

Upvotes: 2

Andrei Sfrent
Andrei Sfrent

Reputation: 189

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).

Upvotes: 7

Related Questions