Question

I'm not even sure if what I want is possible, but I'd like to run a Cron job where an email is only sent in certain conditions. I know that you can prevent mail from being sent at all by setting MAILTO to an empty string in the crontab file, but I've searched in several different ways, and can't find anything about sending email conditionally. My end goal is to run a Cron job that periodically checks whether the webserver is running, and if not, restart it. I only want an email if the webserver has to be restarted. I'm writing my Cron jobs in Perl. Is there a Perl command I can use within the job script that will disable the email in certain cases? Thanks for any help you can give me.

Was it helpful?

Solution 2

There are 2 possibilities to send mails from cron jobs:

  1. From program, that has been started by cron daemon,

  2. From UNIX/Linux mechanism, that can send mail, if a program, that has been started as a cron job, has written something to STDOUT or STDERR.

I don't recommend to use the 2nd possibility. It is inflexible. You can't send mails to different recipients, depending on what alert has happened. Usage of the 2nd way is rather a bad design. Cron jobs should redirect all their stdout and stderr to an idividual for every cron job log file for possible troubleshooting.

Perl possesses perfect possibilities to send mails, e.g. using MIME::Lite module. This module is not a core one, so that you might should request sysadmin to install this module, if it's not available. If you will use the 1st way, then your issue is easy to solve using Perl logic: just send the required mail from your Perl program after this program restarted the web server.

OTHER TIPS

Cronjobs will send emails if the command you are running generate output. If you write your script to only send output to STDERR/STDOUT when you want an email, that should accomplish your goal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top