4

Firstly, I'm using VS2008 (doesn't support C++11). I can't upgrade and need to use native libraries only because it needs to be compiled on another persons' compiler which I don't have control over.

I would like to run the code automatically after 5 seconds without having to poll how many seconds have elapsed.

This is my incomplete code

#include <windows.h>
#include <iostream>
void runMeAfterFiveSeconds(){
     cout<<"I'm activated!"<<endl;
}
void main(){
     while(1){
          cout<<"hello there!"<<endl;
          Sleep(2000);
     }
}

Example output

hello there!
hello there! //after 2 seconds
hello there! //after 4 seconds
I'm activated! //after 5 seconds
hello there! //after 6 seconds
hello there! //after 8 seconds
hello there! //after 10 seconds
I'm activated! //after 10 seconds
...
John Evans Solachuk
  • 1,953
  • 5
  • 31
  • 67

4 Answers4

5

This example shows how to do it using a very simple scheduling algorithm. No spawning of additional threads is required.

#include <stdio.h>
#include <windows.h>

int main(int argc, char ** argv)
{
   DWORD now                      = timeGetTime();
   DWORD nextPrintHelloThereTime  = now;
   DWORD nextPrintImActivatedTime = now+5000;

   while(1)
   {
      now = timeGetTime();
      DWORD nextEventTime = (nextPrintHelloThereTime < nextPrintImActivatedTime) ? nextPrintHelloThereTime : nextPrintImActivatedTime;

      DWORD millisecondsToSleep = nextEventTime-now;
      Sleep(millisecondsToSleep);

      now = timeGetTime();
      if (now >= nextPrintHelloThereTime)
      {
         printf("hello there!\n");
         nextPrintHelloThereTime += 2000;
      }
      if (now >= nextPrintImActivatedTime)
      {
         printf("I'm activated!\n");
         nextPrintImActivatedTime += 5000;
      }
   }
}
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
  • I got this error `error LNK2019: unresolved external symbol __imp__timeGetTime@0 referenced in function _main`. did u miss out any header files? – John Evans Solachuk Dec 21 '14 at 04:08
  • What you are seeing is a linker error. timeGetTime() is part of the Windows multimedia library, so you need to link in that library (which is included standard in all versions of Windows starting with Windows 2000) by adding winmm.lib to the list of libraries you are linking in to your program. – Jeremy Friesner Dec 21 '14 at 04:21
  • 1
    Alternatively you can add this line to the top of the of the file: #pragma comment(lib,"winmm.lib") – Jeremy Friesner Dec 21 '14 at 04:24
2

It really depends on what code you want to execute and how you want it to be executed. The very simple way of doing so would be creating a separate thread and Sleep() in it. So, since you cannot upgrade from Visual Studio 2008 (which, if I remember correctly, does not support C++11), you have to use either native Windows threads or some library implementation like Boost.Thread. To look up how to use Windows threads, see MSDN documentation on _beginthreadex() function. A short tutorial about Boost.Thread can bee seen here.

Quick examples of both, taken directly from the links I provided:

1) Windows threads:

// crt_begthrdex.cpp
// compile with: /MT
#include <windows.h>
#include <stdio.h>
#include <process.h>

unsigned Counter; 
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
    printf( "In second thread...\n" );

    while ( Counter < 1000000 )
        Counter++;

    _endthreadex( 0 );
    return 0;
} 

int main()
{ 
    HANDLE hThread;
    unsigned threadID;

    printf( "Creating second thread...\n" );

    // Create the second thread.
    hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );

    // Wait until second thread terminates. If you comment out the line
    // below, Counter will not be correct because the thread has not
    // terminated, and Counter most likely has not been incremented to
    // 1000000 yet.
    WaitForSingleObject( hThread, INFINITE );
    printf( "Counter should be 1000000; it is-> %d\n", Counter );
    // Destroy the thread object.
    CloseHandle( hThread );
}

2) Boost.Thread:

struct callable
{
    void operator()();
};

boost::thread copies_are_safe()
{
    callable x;
    return boost::thread(x);
} // x is destroyed, but the newly-created thread has a copy, so this is OK

In the second example, you could as well have used a plain function pointer as boost::thread constructor argument. Moreover, you could use a pointer to function with multiple arguments - a luxury Windows API's threads do not provide.

UnknownGosu
  • 854
  • 6
  • 9
  • I can't use Boost since the person who receives my code needs to compile my code in his platform and he might not have Boost. I will try out the first one. – John Evans Solachuk Dec 21 '14 at 02:54
-3

You're probably just going to need to create a thread like so:

#include <windows.h>
#include <iostream>
#include <thread>
void runMeAfterFiveSeconds(){
     while(true){
          sleep(5000);
          cout<<"I'm activated!"<<endl;   
     }     
}
void main(){
     std::thread th(runMeAfterFiveSeconds);
     while(1){
          cout<<"hello there!"<<endl;
          Sleep(2000);
     }
}
Coding Orange
  • 548
  • 4
  • 7
-3

You're going to have to either make a thread (Coding Orange's answer, probably the better way), or just write it all out.

void runMeAfterFiveSeconds(){
     cout << "I'm activated!" <<endl;        
}

void main(){
     while(1){
          cout << "hello there!" << endl;
          Sleep(2000);
          cout << "hello there!" << endl;
          Sleep(3000);
          runMeAfterFiveSeconds();
          Sleep(1000);
          cout << "hello there!" << endl;
          Sleep(2000);
          cout << "hello there!" << endl;
          Sleep(2000);
          cout << "hello there!" << endl;
          runMeAfterFiveSeconds();
     }
}
aspin
  • 309
  • 2
  • 12