Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

infinite loops (sorta) any efficient way to do this?

Status
Not open for further replies.

m4trix

Vendor
Jul 31, 2002
84
CA
Essentially, I want a script to run for as long as it takes, when the time is a certain time, I want the script to execute a command.

I just did it by going:
[tt]
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;

while($min < 59 && $hour == 17){
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
if($min == 58) {print &quot;Its almost 6 pm\n&quot;;last;}

}
print &quot;done&quot;;[/tt]

and basically that's a simplified version, but if I run that at like 5:30, it will loop until 5:58 is reached, print that statement, and exit the loop.

This seems incredibly inefficient. First off, I like to avoid breaking out of a loop that way if possible, secondly, that will just loop several billion times waiting. Is there any way around this? for example can you get it to loop every 30 seconds or something? save CPU power...
 
[tt]use Time::Local;

# use to get current date
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;

# get seconds since epoch of time we want to wake up
$waketime = timelocal(0, 59, 17, $mday, $mon, $year);

if ($waketime > time) {
sleep $waketime - time;
print &quot;It's almost 6pm\n&quot;;
} else {
print &quot;Too late.\n&quot;;
}[/tt]

This only works if you're not trying to sleep until sometime tomorrow. If you need to get more complicated, you'll likely need to use some date calculations like in Date::Calc

Alternatively, you could still use a [tt]while[/tt] loop like you are and throw in a [tt]sleep 10;[/tt] to only check every 10 seconds (or however long you can sleep without making your result happen too late.)
 
You can sleep for 250 milliseconds (a quarter of a second) like this:

select(undef, undef, undef, 0.25); Mike

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

It's like this; even samurai have teddy bears, and even teddy bears get drunk.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top