views:

78

answers:

2

I want my .pl to execute a function at the end of every day, week and month. What the function will do is grab an integer from an html at the end of the day and store it in a .txt to be used to create a graph.

I already know how to implement CGI and JS with a perl script, so that is no issue. I'm just not clear on whether or not DateTime objects can be used in this boolean-type way. This sounds simple, so I hope there is a simple answer.

+3  A: 

It's unclear whether your solution MUST be all-perl or not.

If NOT all-perl, you can do something "at the end of every day" and "at teh end of every week" (the latter just means end of Sunday) using your system's scheduler (cron on Unix/Linux/MacOS, AT pr Windows Scheduler on Windows).

For end of month, you can run the script every day but at the beginning, quit if not end of month. The logic for both end of month (and end of week as a bonus) would be using something like:

use Time::Local qw ( timelocal_nocheck ); 
my @time_data = localtime() ; 
my $current_dom = $time_data[3];
my $current_dow = $time_data[6];
$time_data[4]++;   # Next month.
$time_data[3] = 0; # Last day of previous month.
@time_data = localtime ( timelocal_nocheck ( @time_data ) );
if ($current_dom == $time_data[3]) {
    # Do end of month processing
}
if ($current_dow == 0) { # Sunday
    # Do end of week processing
}

Hat tip: http://www.perlmonks.org/?node_id=418897

DVK
Apologies for the ambiguity, but it is meant to be an all-perl solution, thanks. This has helped a lot.
Dorian
A: 

Here is a simple example of how to use DateTime to trigger a function:

use 5.012;
use warnings;
use DateTime;

my $now = DateTime->now;

# example queue
my @jobs = (
    { after => $now->clone->subtract( hours => 1 ), sub => undef },  # done
    { after => $now->clone->subtract( hours => 1 ), sub => sub{ say "late"  }},
    { after => $now->clone,                         sub => sub{ say "now"  }},
    { after => $now->clone->add( hours => 1 ),      sub => sub{ say "not yet" }},
);

for my $job (@jobs) {
    if ($job->{after} <= $now && $job->{sub}) {
        $job->{sub}->();
        $job->{sub} = undef;   # ie. clear from queue
    }
}

The above will run late & now only.

There are a couple of DateTime modules on CPAN which may help further.

Alternatively there is a complete cron clone called Schedule::Cron

draegtun