Click here to Skip to main content
15,900,511 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there a timer class to use in a c++ console app?

I need a timer to delaying an output to a user.
Posted
Updated 20-Jun-18 7:32am

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.

C++
#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.

C++
#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.
 
Share this answer
 
You could use the Sleep() function within a loop to delay your process.
 
Share this answer
 
#include "stdafx.h"
#include <Windows.h>
#include <iostream>

using namespace std;

BOOL quit = FALSE;

void timertick(int count)
{
	char buff[64];
	_itoa_s(count, buff, 64,10);
	cout << buff<<"\n";

}
DWORD WINAPI thread1(__in LPVOID lpParameter) {
	int nCount = 0;
	HANDLE hTimer = CreateEvent(NULL, FALSE, FALSE, NULL);
	while (!quit)
	{
		
			WaitForSingleObject(hTimer, 1000);
			//cout << "1 s\n";
			nCount++;
			timertick(nCount);
		
	}
	return 0;
}


int main()
{

	DWORD threadID1;
	HANDLE h1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread1, 0, 0, &threadID1);
	//HANDLE h2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread2, 0, 0, &threadID2);

	getchar();
	quit = TRUE;
	return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900