Start Service if not running using CRON Job Ubuntu Linux

Sometimes the services which are intended to run all the time will stop for some reason, the server or the tool need to react to this situation to keep the downtime minimal

In this post, we will create a script that checks for the status of the service and start it if not running and execute the script periodically using the CRON job.

Watch Script

Save the below script in the /usr/bin or any other directory

#!/bin/bash
service=ha-service

if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
then
  echo "$service is running!!!"
else
  /etc/init.d/$service start
fi

or instead of checking the process running, you can directly check using the systemctl command

#!/bin/bash
service=ha-service

/bin/systemctl -q is-active "$service.service"
status=$?
if [ "$status" == 0 ]; then
   echo "$service is running!!!"
else
   /bin/systemctl start "$service.service"
fi

Note: Don’t forgot to replace the “ha-service” with your service name

If you want to make the script generic, instead of hardcoding the service name in the file, take it from the argument and replace the value of service with $@

CRON Job

You can add a schedule according to your accepted downtime or SLA, you can run it every minute as well. To install the above script as a CRON job, run the below command and open it with your preferred editor

sudo crontab -e

Below are some examples for the crontabs

0 */2 * * *   /usr/bin/service-watcher > /dev/null
0 0 */1 * *   /usr/bin/service-watcher > /dev/null
* * * * *   /usr/bin/service-watcher > /dev/null

0 */2 * * * Runs every two hours

0 0 */1 * * Runs At 00 minutes past 0:00 on every 1 day of every month

* * * * * Runs every minute


Also published on Medium.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.