Here is yet another example using Windows Waitable Timer. Short quote from MSDN page:
A waitable timer object is a synchronization object whose state is set to signaled when the specified due time arrives. There are two types of waitable timers that can be created: manual-reset and synchronization. A timer of either type can also be a periodic timer.
Example:
#include <Windows.h>
#include <iostream>
void main(int argc, char** argv)
{
HANDLE hTimer = NULL;
LARGE_INTEGER liTimeout;
// Set timeout to 10 seconds
liTimeout.QuadPart = -100000000LL;
// Creating a Waitable Timer
hTimer = CreateWaitableTimer(NULL,
TRUE, // Manual-reset
"Ten-Sec Timer" // Timer's name
);
if (NULL == hTimer)
{
std::cout << "CreateWaitableTimer failed: " << GetLastError() << std::endl;
return;
}
// Initial setting a timer
if (!SetWaitableTimer(hTimer, &liTimeout, 0, NULL, NULL, 0))
{
std::cout << "SetWaitableTimer failed: " << GetLastError() << std::endl;
return;
}
std::cout << "Starting 10 seconds loop" << std::endl;
INT16 count = 0;
while (count < SHRT_MAX)
{
// Wait for a timer
if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0)
{
std::cout << "WaitForSingleObject failed: " << GetLastError() << std::endl;
return;
}
else
{
// Here your code goes
std::cout << count++ << std::endl;
}
// Set a timer again
if (!SetWaitableTimer(hTimer, &liTimeout, 0, NULL, NULL, 0))
{
std::cout << "SetWaitableTimer failed: " << GetLastError() << std::endl;
return;
}
}
}
Also, you can use a Waitable Timer with an Asynchronous Procedure Call. See this example on MSDN.