1

I work on VC++ 2008 in a console application. I want to call a function every x seconds. I have a piece of code but the problem is that the code behind the setTimer does not execute. I am looking something like a simultaneous timer or thread, but as my c++ version is old I cant include thread or chrono. Can anyone help me? Thanks in advance.

The code is here:

void CALLBACK f(HWND hwnd, UINT uMsg, UINT timerId, DWORD dwTime){cout <<"Hello";}

int _tmain(){
MSG msg;
SetTimer(NULL, 0, 100*60,(TIMERPROC) &f);
while(GetMessage(&msg, NULL, 0, 0)) 
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
//more code to be execute, but it does not.
return 0;}

This question has been marked as a duplicate, but the problem is not that the message is not shown, that is correct. The problem is to create a timer and run the program simultaneously.

Andermutu
  • 124
  • 2
  • 16

1 Answers1

0
#include <time.h>

float timeDelta = 0;
clock_t clk = clock(), temp;

while (timeDelta <= /*NumSecondsDesire*/)
{
    temp = clock() - clk;
    clk = clock();
    timeDelta += (float)((float)temp / CLOCKS_PER_SEC);
}

That should do it for you. clock() returns the number of clicks, and you divide that by the processor specififc CLOCKS_PER_SEC to get the number of seconds. You might want the case in an if-statement, in which case, reset timeDelta to = 0 at each iteration where timeDelta = NumSecondsDesired.

  • 3
    Busy-wait polling might be a good way to get laughed outta job. – n. m. could be an AI Jul 17 '17 at 09:04
  • Thanks Zach. With this code is possible to keep running the program until enters in the clock? – Andermutu Jul 17 '17 at 09:05
  • @Andermutu if you mean, can you keep the program running until it reaches the time-limit? Then yes. Just have the while condition enclosing your main program loop and have the code above in the order listed, otherwise the amount of time it actually takes will be skewed from what your program is saying. – Zach Hammond Jul 17 '17 at 09:10
  • Thanks again Zach, but I get this error. 'Error 1 error C3861: 'clock': no se encontró el identificador c:\Users\P\Documents\Visual Studio 2008\Projects\Timer 3\Timer 3\Timer 3.cpp 9 Timer 3 ' – Andermutu Jul 17 '17 at 09:33
  • Maybe I need to include sometheing else? – Andermutu Jul 17 '17 at 09:33
  • Also, try copying in my code, see if that works. I updated it so it has less of a time skew when there's less code between each setting of the time. – Zach Hammond Jul 17 '17 at 09:49