Call a function every x seconds

2

I'm doing a console application in VS2008. I have a function that I have to call it every 5 seconds, but until those 5 seconds pass the program has to keep running. I have tried to use thread, but I can not include it because my version of c ++ is old. I have taken another path and I get to call the function every 5 seconds but while the code is not executed. Thanks in advance.

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);
}
//mas codigo a ejecutar pero que no consigo...
return 0;}

In the end I managed to solve the problem in this way:

DWORD WINAPI solo_thread(void* arg){
int Counter = 0;
printf( "In second thread...\n" );

while ( true )
{
    if(Counter<10)
    {
        Counter++;
        Sleep(1000);
    }
    else 
    {
        printf( "Han pasado 10 segundos; Counter:-> %d\n", Counter );
        funcionalarm();
        Counter = 0;
    }

}

return 0;}

int _tmain(){
int x=0;
HANDLE hThread;
while (true)
{
    printf( "Creating second thread...\n" );
    hThread = CreateThread(NULL, 0, solo_thread,NULL ,0, NULL);
    //WaitForSingleObject( hThread, INFINITE );
    CloseHandle( hThread );
    while (x<10)
    {
        cout <<x;
        x=x+1;
        Sleep(1000);
    }
    x=0;    
}

Sleep(6000);
return 0;}
    
asked by Andermutu 17.07.2017 в 11:44
source

1 answer

4

If you can not use the thread library then you can choose to resort to a library that provides an equivalent implementation (for example Qt or boost) or you can paste directly with the Windows API.

I recommend the first option since programming on WinAPI usually ends in constant headaches.

A possible example with boost:

#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <iostream>

void thread()
{
  try
  {
    while( true )
    {
      funcionALlamarCada5Segundos();
      boost::this_thread::sleep_for(boost::chrono::seconds{5});
    }
  }

  catch( boost::thread_interrupted const& )
  { }
}

int main()
{
  boost::thread t{thread};

  // tu codigo aqui

  // Finalizamos el hilo
  t.interrupt();
  t.join();
}
    
answered by 17.07.2017 / 11:56
source