How to install crontab work for perl script

I have a Perl script that I want to run every 4 hours through cron. But somehow it cannot execute through cron and works fine if I run it through the command line. The following is the command I installed in crontab:

perl -q /path_to_script/script.pl > /dev/null 

Also, when I run this command on the command line, it is not executed, but when I go to the worksheet folder in path_to_script and execute the file, it works fine.

Also, where will the log files of this cron job be created so that I can view them?

+4
source share
4 answers

You should probably change the working directory to a "worksheet folder".

Try this on your crontab command:

 cd /path_to_script; perl script.pl >/dev/null 

Wrt. log files. Cron will send you a message. But since you sent stdout to / dev / null, only stderr will be sent to you.

If you want the result to be stored in a log file, then output the output of stderr / stdout from the script to a file, for example:

 cd /path_to_script; perl script.pl 2>&1 >my_log_file 
+8
source

Usually cron will send you a message with the output of your program. When you find out, you probably want to check the environment. This will not necessarily be the same environment as your login shell (since it is not a login shell):

  foreach my $key ( keys %ENV ) { printf "$key: $$ENV{$key}\n"; } 

If you are missing something you need, install it in your crontab:

  SOME_VAR=some_value HOME=/Users/Buster 

If you need to start in a specific directory, you should chdir there. The initial directory from the cron job is probably not the one you think so. Without an argument, chdir changes to your home directory. However, sometimes these environment variables cannot be set in your cron session, so it is probably best to have a default value:

  chdir( $ENV{HOME} || '/Users/Buster' ); 

At different critical points you should give an error message. This is good even in programs other than cron:

  open my $fh, '<', $some_file or die "Didn't find the file I was expecting: $!"; 

If you redirect things to / dev / null, you lose all the information that may help you solve the problem.

+2
source

it looks like you might have missed

 #!/usr/bin/perl 

at the beginning of your perl script, so you may need perl -q to run it after you add this line, you can run it directly from the command line using

 /path_to_script/script.pl 
-1
source

If you use a command in your perl program, I advise you to put the full path to the command in your program.

I am trying to load the medium, but it is no more useful.

After observing with one colleague, I think this is due to the interaction between perl and the system environment.

Regards, Mustafa Kuruma

-3
source

Source: https://habr.com/ru/post/1403201/


All Articles