Mohamed Helal
Mohamed Helal

Reputation: 43

Unable to run Perl script from cron

I have a script that run correctly from bash but does not run when i try runnning it from 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 = '[email protected]';
$cc = $backup_email . ', [email protected]' ;
$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";

This is my cron

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

When i check the log file, the only thing printed is "Starting perl script:"

I have tried adding environment variables to another file and calling the Perl script itself but still got no luck. I am guessing that I should add environment variables to Perl script but not sure how to do so.

Upvotes: 1

Views: 156

Answers (1)

Georg Mavridis
Georg Mavridis

Reputation: 2331

You can add/set Environment-Variables in the perl script by using:

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

but you probably should set them in your crontab entry instead. E.g.

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

To locate your mistake, you can wrap your relevant code into a try-catch block called "eval" in perl.

...
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 $@";
};

Upvotes: 1

Related Questions