Sleep() is a simple solution. However, it is not all. You can make a timer out of a kernel object too. You would have to use WaitForSingleObject(...) which takes the intended milliseconds as the second parameter. The following code prints every one second and counts for 10 seconds.
#include <windows.h>
void main()
{
int nCount = 0;
HANDLE hTimer = CreateEvent(NULL, FALSE, FALSE, NULL);
while(nCount < 10)
{
WaitForSingleObject(hTimer, 1000);
cout << "1 s\n";
nCount++;
}
cout << "10 secs\n";
CloseHandle(hTimer);
}
This is tedious compared to Sleep() as I said but still is a way to do it, especially if you want to break the wait cycle due to some event that has occurred. The following code illustrates that.
#include <windows.h>
HANDLE hTimer = NULL;
unsigned long _stdcall Timer(void*)
{
int nCount = 0;
while(nCount < 10)
{
WaitForSingleObject(hTimer, 5000);
cout << "5 s\n";
nCount++;
}
cout << "50 secs\n";
return 0;
}
void main()
{
DWORD tid;
hTimer = CreateEvent(NULL, FALSE, FALSE, NULL);
CreateThread(NULL, 0, Timer, NULL, 0, &tid);
int t;
while(cin >> t)
{
if(0==t)
SetEvent(hTimer);
}
CloseHandle(hTimer);
}
If you type a zero then the timer will be canceled immediately. If not, it will go on to wait for at least 5 seconds.