Windows – Wait/Pause an amount of seconds in C

c++windows

I wrote a little console application, and I want it to pause for a certain number of seconds before the cycle (a while) starts again.

I'm working on Windows operating system.

Best Solution

On Windows, the function to do this is Sleep, which takes the amount of milliseconds you want to sleep. To use Sleep, you need to include windows.h.

On POSIX-Systems, the function sleep (from unistd.h) accomplishes this:

   unsigned int sleep(unsigned int seconds);

   DESCRIPTION
          sleep()  makes  the  calling thread sleep until
          seconds seconds have elapsed or a signal arrives which is not ignored.

If it is interrupted by a signal, the remaining time to sleep is returned. If you use signals, a more robust solution would be:

 unsigned int time_to_sleep = 10; // sleep 10 seconds
 while(time_to_sleep)
     time_to_sleep = sleep(time_to_sleep);

This is of course assuming your signal-handlers only take a negligible amount of time. (Otherwise, this will delay the main program longer than intended)