Reputation: 259
I'm wondering how to make a time delay of a few seconds using C , without using while loop. The samples I got are using while loop. This works but I dont want to use the while loop. Please help
while(clock() < endwaitTime)
{
if(!GetFlag())
{
print(" Canceled ");
return ;
}
}
Upvotes: 3
Views: 1361
Reputation: 27874
You can use sleep()
to pause your application for the given amount of seconds, or you can use usleep()
to pause your application for the given amount of microseconds.
You can also explore the blocking properties of select()
to have a microsecond precision pausing. Some applications prefer to do that, don't ask me why.
About your while()
loop, never do that. It is not pausing. Your application will loop using 99% of the CPU until the time has elapsed. Its a very dumb way of doing that.
Also, its preferable that you use time()
to get the current UNIX time and use that as reference, and difftime()
to get the time delta in seconds to use with sleep()
.
You may have problems with clock()
, because this function on a 32-bit system will return the same number every ~72 minutes, and you will often have a endwaitTime
with lower value than the current return value of clock()
.
Upvotes: 3
Reputation: 27433
Following http://linux.die.net/man/3/sleep
#include <unistd.h>
...
// note clock() is seconds of CPU time, but we will sleep and not use CPU time
// therefore clock() is not useful here ---
// Instead expiration should be tested with time(), which gives the "date/time" in secs
// since Jan 1, 1970
long int expiration = time()+300 ; // 5 minutes = 300 secs. Change this as needed.
while(time() < expiration)
{
sleep(2); // dont chew up CPU time, but check every 2 seconds
if(!GetFlag())
{
print(" Canceled ");
return ;
}
}
...
Of course, you can get rid of the while loop completely if a single sleep() is good enough. For a short pause this may be OK. Input is still queued by Linux while the process is sleeping, and will be delivered to the stdin of the program when it wakes up from the sleep.
Upvotes: 1