User
User

Reputation: 24759

Cronjob to check and restart service if dead

I want a 1 liner that can check and restart services, such as Apache if they are inactive/dead.

I want to put it in crontab and run it every minute to make sure the service is still running.

Upvotes: 7

Views: 24991

Answers (4)

M1GEO
M1GEO

Reputation: 283

Sorry for waking up a sleeping thread, but as many of the answers no-longer work and I found this page while looking, I figured I'd add my solution here:

Create script check_service.sh and set SERVICENAME as desired:

#!/bin/bash

SERVICENAME="WHATEVER_SERVICE_YOU_WANT"

systemctl is-active --quiet $SERVICENAME
STATUS=$? # return value is 0 if running

if [[ "$STATUS" -ne "0" ]]; then
        echo "Service '$SERVICENAME' is not curently running... Starting now..."
        service $SERVICENAME start
fi

Make the script executable:

chmod +x check_service.sh

Finally, add the script to Root's crontab by running sudo crontab -e:

# min   hour    day month   dow cmd
*/1 *   *   *   *   /full/path/to/check_service.sh

Save the crontab, and wait patiently!

Upvotes: 17

Seva Kobylin
Seva Kobylin

Reputation: 109

You can use special software like monit for this case. It can check your daemons , restart it if needed and send you alerts. Another good option -- it can stop try to restart service after N fails (for example if service cannot start).

Upvotes: 2

NarūnasK
NarūnasK

Reputation: 4950

service_ck.sh

#!/bin/bash
STATUS=$(/etc/init.d/service_name status)
# Most services will return something like "OK" if they are in fact "OK"
test "$STATUS" = "expected_value" || /etc/init.d/service_name restart

Change file permissions:

chmod +x service_ck.sh

Update your crontab:

# min   hour    day month   dow cmd
*/1 *   *   *   *   /path/to/service_ck.sh

Upvotes: 6

mmccaff
mmccaff

Reputation: 1281

If you save this as a bash script it will be a one-liner that you can call from cron. This will restart Apache if it's not in the process list returned by pgrep.

Obviously this assumes that you have pgrep. Adjust your command to restart accordingly.

If Apache is running but not responsive, that is a different issue. You'd have to check that some endpoint is responding (and responding correctly) within a specified timeout, etc.

#!/bin/bash

RESTART="/etc/init.d/httpd restart"
PGREP="/usr/bin/pgrep"
HTTPD="httpd"

$PGREP ${HTTPD}

if [ $? -ne 0 ] # if apache not running 
then
 # restart apache
 $RESTART
fi

Upvotes: 1

Related Questions