Time::Left

CPAN version License

Simple Perl module for tracking time limits or deadlines.

Synopsis

use Time::Left qw(time_left);

# Progress indicator with time limit.
local $! = 1;
print "Working ...";
my $timer = time_left("10s");
until (done() or $timer->expired) {
    Time::HiRes::sleep(0.25);
    print ".";
}
die " timed out.\n"
    unless done();
print " done.\n";

Key Features

Installation

cpanm Time::Left

Basic Usage

Creating Timers

use Time::Left qw(time_left to_seconds);

# From duration strings
my $timer = time_left("1m");   # 60 seconds
my $timer = time_left("2.5h"); # 2.5 hours

# From seconds
my $timer = Time::Left->new(60); # 60 seconds

# Indefinite (no timeout)
my $timer = time_left(undef);

Checking Status

my $sec = $timer->remaining;   # Seconds left (or undef if indefinite)
my $active = $timer->active;   # True if time remains
my $expired = $timer->expired; # True if time is up

# Boolean context uses active/expired
while ($timer) {
    # Still time left
}

if (!$timer) {
    # Timer expired
}

Common Patterns

Time-limited socket read:

if (IO::Select->new($socket)->can_read($timer->remaining)) {
    $socket->recv($buffer, 1024);
    # Process data...
}

Conditional timeout setup:

# Set up alarm if timer is limited
Time::HiRes::alarm($timer->remaining)
    if $timer->is_limited;

API Quick Reference

Functions

Methods

Requirements

License

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

Author

Brett Watson

See Also