2

I have a Perl script which runs 2 times a day using cron. I would like to know a command to check when my Perl program last ran. Does such command exists? If not, can you guys please tell me how will I accomplish this task?

Jacob
  • 105
  • 1
  • 1
  • 7
  • 3
    You should be able to interpret that from the crontab entry. `0 0,12 * * *` would run at noon and midnight. Otherwise, alter the script to log when it runs, or wrap it in a shell script which does that and run that from cron instead. – Schwern May 25 '18 at 19:07
  • 1
    Some systems log cron jobs in /var/log. Look [here](https://askubuntu.com/questions/56683/where-is-the-cron-crontab-log) for more info. – pcjr May 26 '18 at 04:37

2 Answers2

2

At the top of your script, put

open LAST, ">", "/tmp/last.time.the.program.ran";
print LAST scalar localtime;
close LAST;

Now the command to see when your program last ran is

$ cat /tmp/last.time.the.program.ran

(You could also poke around /var/log/cron)

mob
  • 117,087
  • 18
  • 149
  • 283
  • 3
    Don't use bareword filehandles for no reason. Always check the return value of `open`. `/tmp/last.time.the.program.ran` is a pretty bad filename to use. This code is open to symlink attacks. – melpomene May 25 '18 at 19:10
0

To answer your first question, no, there is not a generalized way to know the last time a program was run. And it's more complicated in this case, since a perl script isn't really a program - the perl interpreter is the executable and the script is the input to the interpreter. So you'd really want to know the last time the perl interpreter was run and executed your script.

Some mechanisms that run other programs (like cron) may keep log files that record when programs are run (and maybe their exit code or other information about the execution). Note: this would not log every time this program was run - just when it was executed via cron. Similarly, you could add some logging to your script to write to a file that it was run. Though if the script failed to run, or could not write to the log file (say, for instance, your permissions were messed up), then it would not log that execution. So it's not a fool-proof solution. But it might be enough for your purposes.

As for cron logging, you can man cron or man crontab, or look at some of the SO questions directly about cron logging. For example, cron jobs - how to log?

Doug
  • 644
  • 1
  • 6
  • 22