[Dub-pm] Time::Piece && while loops

Gary Cosgrave sucellus at eircom.net
Thu May 6 05:53:36 CDT 2004


If worried about localtime(time()) overheads - you could easily add a check to
avoid it, without the perils of alarm() and eval().  Also, we can dodge DST
issues with a constant, that we could even change to a low value during DST safe
times of the year to maximise efficency.

For instance:

# Constant that is safe 365 days
use constant DST_THRESHOLD => 3601;

# Setup some globals

my ($midnight,$current_date) = &reset_midnight();
my $current_file_date = $current_date;
my $current_fh = &refresh_filehandle($current_date);

# At each log event

while (my $msg=<$in>) {
    $now=time();
    if ( ( $now - $midnight ) > ( 24*60*60 - DST_THESHOLD ) ) {
    # time_to_change_files does the localtime($time) work
    if ( &time_to_change_files($current_date) ) {
        ($midnight,$current_date)=&reset_midnight();
        $current_fh=&refresh_filehandle($current_date);
    }
    &log_msg($current_fh,$msg);
}

sub reset_midnight {
    my $now=time();
    my ($sec, $min, $hour, @slurp_time) = localtime($now);
    $current_date = some_calculation_based_off_slurp_time;
    my $midnight = $now - ( $hour*60*60 + $min*60 + $sec );
}

Fergal Daly wrote:

> sub tomorrow
> {
>         # figures out when tomorrow starts in terms of seconds from epoch so
>         # that it can be compared directly with a value given by time()
>
>         my ($sec, $min, $hour) = localtime(time());
>         my $tomorrow = $now - (($hour*60) * 60 + $sec) + 24*60*60;
>
>         return $tomorrow;
> }

Small pedantic point:

It does seem that this sub could run into a few DST issues, particularly
assuming that it is used to set $tomorrow early each day (assuming a relatively
busy log file (1 msg/minute?).  Either way, in Spring for instance, $tomorrow
would represent 1am the next day, and 11pm the same day in Autumn.

And no, I haven't been stung by these issues a hundred times...honest.

> A more efficient solution (the most efficient?) would be to use eval{} and
> alarm() to set a timer to go off when tomorrow arrives but that'd be
> overkill and has nasty pitfalls for a very small improvement over the code
> above,
>
> F




More information about the Dublin-pm mailing list