As explained here, the Windows API GetMessage()
blocks until a message is available.
I would like to automatically wake after n seconds. Alternatively, I'd like to have the system post a WM after n seconds. Is there a way to do that?
My current code uses an alternate approach, explained here, where I use a second thread, and have it sleep for n seconds. But the multithreading is causing problems. I'd like to try to use only a single thread, but just make sure it always wakes up after n seconds, even if no other "natural" WM has been posted.
As the comments say, this is straightforward. WM_TIMER
is the designated message for this. You call SetTimer
to schedule it, KillTimer
to stop receiving them.
Behind the scenes, there's an optimized mechanism to deliver WM_TIMER
messages. They don't exist as-is in the message queue, but are synthesized when retrieved.
A less-direct answer is to use MsgWaitForMultipleObjectsEx
. This avoids the need for SetTimer/KillTimer
as it directly accepts a timeout value. In addition, it can also check for IO events.