Search code examples
linuxperlcentoscroncron-task

Perl & Linux? : Make a log reader script run daily and weekly (automatic)


We have a Log reader script, for example:

use strict;
use warnings;

my $location = "file.txt";
open LOGFILE, $location;

my $first_line = 1;
my $max_id;

while (<LOGFILE>) {
    if (/item_id:(\d)+/) {
        if ($first_line) {
            $first_line = 0;
            $max_id = $1;
        } else {
            $max_id = $1 if ($1 > $max_id);
        }
    }
}

my $found = $max_id;
print "$found\n";

close LOGFILE;

(code by @duskast)

And we need this code to run automatically on a daily basis, say every day at 7 am, and also on a weekly basis.

I know that to run this daily there is a "cron" command or some shell script, as we are using linux here, but I have never used that command.

Also, how about weekly? That would be the sum of the latest 7 days, so perhaps that can be done with Perl?


Solution

  • cron and crontab is what you should use.

    the standard format for using cron is:

        Minute Hour Day_of_Month Month Day_of_Week Cmd
    

    so running

        25 07 05 * * /home/user/log_reader.pl
    

    will run 7:25am on the 5th of each month (asterisk allows any month) any weekday (asterisk selectts any week day allowed)

    So your cron job..

        00 6 * * * /home/user/log_reader.pl
    

    is running 6:00am each_month, everyday.

    this one,

        00 6 * * 3 /home/user/log_reader.pl
    

    will run 6:00am on 3rd day of the week, meaning once a week.

    Hope that helps.