Create mail lock in perl script

时间:2015-07-28 16:14:18

标签: perl

I am trying to run a perl script as cron to send mails to me if a certain condition is met. I am doing this to run every 15 mins. However, I want to limit my script from generating a mail when it has sent a mail in the last 60 mins.

Here's the code snippet i am using to achieve that, but this doesn't seem to work.

use strict;

my $Mailed = 0;
if ( !-f `/tmp/Mail.lock` ) {
    $Mailed = 1;
}
else {
    my $om = `find /tmp/Mail.lock -mmin +60`;
    if ($om) {
        $Mailed = 1;
    }
}
if ( $Mailed = 1 ) {
    print "Starting " . Now() . "\n";
    print "send mail";
}

Am i missing something? Please help.

2 个答案:

答案 0 :(得分:2)

Turn on warnings too, and you'll get:

Found = in conditional, should be == at  line 12.

Basically - your 'test' doesn't work at all. What are are evaluating is 'did I set $Mailed to 1' and funnily enough it's always working.

Try this snippet:

my $Mailed = 0;
if ( $Mailed = 1 ) { print "Yes\n"; }

Now() isn't a real function either. Maybe you were thinking of time()?

Also - you are testing the text output of find there, rather than the return code. But either way, calling find for a single file, from a perl script is overkill anyway.

I'd also suggest - rather than calling out to find - instead just write to the file and read the mtime via stat.

e.g.:

my $mtime = ( stat($filename) )[9]

next if $mtime > time() - 3600;

Or alternatively, use the '-M' operator:

my $send_inhibit = 1 / 24; # 1 hour in days, because -M $filename returns in days. 
next if -M $filename < $send_inhibit;

Creating the file (when you send a mail) via:

open ( my $lockfile, ">", $filename ) or die $!;
print {$lockfile} time();
close ( $lockfile ); 

答案 1 :(得分:2)

错误#1

-f `/tmp/Mail.lock`

应该是

-f '/tmp/Mail.lock'

前者尝试执行/tmp/Mail.lock,并测试结果(undef)是否是普通文件的名称。

use warnings;已发现此问题。始终使用use strict; use warnings;

错误#2

if ( $Mailed = 1 ) {

应该是

if ( $Mailed == 1 ) {

您将1分配给$Mailed,然后检查它是否为真(显然是这样)。

实际上,它应该如下:

if ( $Mailed ) {

无需检查具体的真实值$Mailed

use warnings;已发现此问题。始终使用use strict; use warnings;

修正:

use strict;
use warnings;

use constant ACTIVITY_QFN => '/tmp/Mail.lock';
use constant COOL_DOWN    => 60*60;

my $mail = 0;
my $mtime = ( stat(ACTIVITY_QFN) )[9];
if (!defined($mtime)) {
   die("Can't stat activity file ".ACTIVITY_QFN.": $!\n")
      if !$!{ENOENT};

   # Activitiy file doesn't exist.
   $mail = 1;
} else {
   $mail = 1 if time() >= $mtime + COOL_DOWN;
}

if ($mail) {
   utime(undef, undef, ACTIVITY_QFN) 
      or warn("Can't touch activity file ".ACTIVITY_QFN.": $!\n");

   ...
}