【问题标题】:Unable to run Perl script from cron无法从 cron 运行 Perl 脚本
【发布时间】:2020-12-21 11:51:10
【问题描述】:

我有一个从 bash 正确运行的脚本,但是当我尝试从 cron 运行它时却没有运行。

use Time::Local;
use DBI;
use MIME::QuotedPrint;
use MIME::Base64;

$dbname1_flip = 'dbi:Oracle:FAM';
$dbuser1_flip = 'sa';
$pass1_flip = 'password';
$DEBUG=1;$primary_email;$backup_email;$primary_name;$backup_name;

$my_log_file="/opt/application/testdir/mylog.log";
open (LOGFILE, ">>$my_log_file") || die "Cannot open log file: $my_log_file\n";
print  LOGFILE "\nStarting perl script: \n";

my $find_queue_manager="select primary_name,Primary_Email,Backup_Name,Backup_Email,Start_Date from table_queue where start_date between sysdate and sysdate + 6";
$dbh1 = DBI->connect($dbname1_flip, $dbuser1_flip, $pass1_flip);
$sth1 = $dbh1->prepare(qq{$find_queue_manager});
$sth1->execute;

while (@row1 = $sth1->fetchrow_array) {
    $primary_email= $row1[1];
    $backup_email= $row1[3];
    $primary_name= $row1[0];
    $backup_name= $row1[2];
    print  LOGFILE  "Primary email is : " . $row1[1]."\n";    
    print  LOGFILE  "Backup email is " . $row1[3]."\n";
}
$sth1->finish;
 
$to = $primary_email ;
$from = 'test@test.com';
$cc = $backup_email . ', dummy@dummy.com' ;
$subject = 'Queue manager (' . $primary_name .')';
$message = "Hello " . $primary_name .",\n" . "\tYou are the primary email \n" .  "\tBackup is " . $backup_name;
 
open(MAIL, "|/usr/sbin/sendmail -t");
 
# Email Header
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Cc: $cc\n";
print MAIL "Subject: $subject\n\n";
# Email Body
print MAIL $message;

close(MAIL);
print LOGFILE "Email Sent Successfully\n";

这是我的计划

37 11 * * 1 /usr/bin/perl /opt/application/p_script.pl

当我检查日志文件时,唯一打印的是“正在启动 perl 脚本:”

我尝试将环境变量添加到另一个文件并调用 Perl 脚本本身,但仍然没有成功。我猜我应该在 Perl 脚本中添加环境变量,但不知道怎么做。

【问题讨论】:

  • tit 是否以正确的用户身份运行?
  • 将use strict; use warnings; 添加到您的代码中。修复产生的错误,用my正确声明变量,然后使用错误日志找出程序没有在cron中运行的原因。
  • 那么你得到了什么错误?至少,该进程有退出代码,但它几乎可以保证向 STDERR 打印了一些东西。
  • 检查邮件假脱机,某处会有实际的错误信息。

标签: perl cron


【解决方案1】:

您可以使用以下方法在 perl 脚本中添加/设置环境变量:

$ENV{ENVNAME} = 'Value I want to set';

但您可能应该将它们设置在您的 crontab 条目中。例如

37 11 * * 1 . /opt/application/envsettings; /usr/bin/perl /opt/application/p_script.pl

要定位您的错误,您可以将相关代码包装到 perl 中名为“eval”的 try-catch 块中。

...
print  LOGFILE "\nStarting perl script: \n";

eval {
my $find_queue_manager="select primary_name,Primary_Email,Backup_Name,Backup_Email,Start_Date from table_queue where start_date between sysdate and sysdate + 6";
...
print LOGFILE "Email Sent Successfully\n";
};

if($@) {
print LOGFILE "Error Executing Script:\n $@";
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 2021-06-22
    • 2014-06-20
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多