How to check if service is running with CRON job?

bash cron services job service

Sometimes might happen that service will stop for some reason. It is good for server to react on this situation. In this article script ran by a CRON job will try to restart service if it is not running. Bash script will check for status code of command systemctl is-active <servicename> and will try to start this service again. Note, that to start service this script must be run by root user.

Script for checking of service availability:

#!/bin/bash

service=$@
/bin/systemctl -q is-active "$service.service"
status=$?
if [ "$status" == 0 ]; then
    echo "OK"
else
    /bin/systemctl start "$service.service"
fi
This script takes one argument, the service name. Lets name it watch-service and place in our home dir's bin directory.

Note that this script requires absolute path to systemctl command to run properly via CRON job.

Example of using script to check for mongod service

Command below will check is mongod service is running. When service is available it will output "OK", if not it will try to start mongod again.

sudo watch-service mongod
Example of adding service watch to CRON job

In this example script will check for mongod and elasticsearch services every minute.

To install it as a CRON job add it to root's crontab with command sudo crontab -e and add following lines, setting up path to script to where You have stored it:

# Ensure service are running
* * * * * /home/peter/bin/watch-service elasticsearch > /dev/null
* * * * * /home/peter/bin/watch-service mongod > /dev/null

There is also output redirection to /dev/null to avoid mailing root that service is OK. See also this project to output services statuses to browser.