Lucas Rey Lucas Rey - 2 months ago 7
Perl Question

While loop until time is reached

I have an application that loops reading a big text file and runs for at least 48 hours.

I would like to stop its execution from 23.00 to 08.00 (11pm to 8am) and then continue its loop during the day.

I tried the following code, but it doesn't exit from the loop.

Edit after Dave Cross' reply



my $min = (localtime)[1];
my $hour = (localtime)[2];

while ( $hour > 18 and $min > 0 ) {
sleep(1);
$hour = (localtime)[2];
$min = (localtime)[1];
}


This doesn't work as expected. Now it's 18:48 and the loop exits immediately unless I use one hour before:

while ( $hour > 17 and $min > 0 )

Answer

You need to check the time more than once :-)

And rather than calling strftime(), why not just use the return value from localtime()?

my $hour = (localtime)[2];

while ($hour >= 23 or $hour < 8) {
  sleep(1);
  $hour = (localtime)[2];
}

Update: A more efficient approach might be to work out how long to sleep() in order to wake up at 8am. A naive approach would be something like this:

if ((localtime)[2]) >= 23) {
  sleep(9 * 60 * 60); # sleep for nine hours
}