Wait/Pause an amount of seconds in C

前端 未结 3 795
温柔的废话
温柔的废话 2021-01-11 12:33

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 operati

相关标签:
3条回答
  • 2021-01-11 12:50

    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)

    0 讨论(0)
  • 2021-01-11 13:01

    easy:

    while( true )
    {
        // your stuff
        sleep( 10 ); // sleeping for 10 seconds
    };
    
    0 讨论(0)
  • 2021-01-11 13:09

    On UNIX:

    #include <unistd.h>
    sleep(10); // 10 seconds
    

    On Windows:

    #include <windows.h>
    Sleep(10000); // 10 seconds (10000 milliseconds)
    

    Note the difference between sleep() (UNIX) and Sleep() (Windows).

    0 讨论(0)
提交回复
热议问题