Search code examples
winapitimerpower-management

How to call SetWaitableTimerEx correctly


We have a long standing bug report in Boost.Thread where apparently thread sleeps will wake the computer from sleep on timer elapse (https://svn.boost.org/trac/boost/ticket/11368). This is apparently due to the new use of SetWaitableTimerEx() to implement coalescing timer support which we call with a REASON_CONTEXT like this:

REASON_CONTEXT default_reason_context={0/*POWER_REQUEST_CONTEXT_VERSION*/, 0x00000001/*POWER_REQUEST_CONTEXT_SIMPLE_STRING*/, (LPWSTR)L"generic"};

If timer firing is causing the PC to wake from sleep, it surely must have something to do with this REASON_CONTEXT value.

Can anyone here tell us what the appropriate value to use to not have the PC wake from sleep on timer expiry?


Solution

  • According to this document from Microsoft: Windows Timer Coalescing, page 8-9:

    SetWaitableTimerEx has two new parameters: WakeContext and TolerableDelay. You use the WakeContext parameter only when you set a timer that can wake the system from a sleep state.

    It looks like passing NULL for the WakeContext parameter is fine and it's the only way SetWaitableTimerEx will not wake the system. Timer coalescing should still work.

    I tried it in Windows 10 and it seems to work correctly. It doesn't wake the system and also doesn't look like it's just calling SetWaitableTimer. It could be different in older versions of Windows though, I haven't tested.