How to Run Cron Job to check and Restart Service If Dead in Linux

This post will guide you how to run a cron job to check and restart process if it isn’t arleary running in your CentOS/RHEL/Ubuntu Server. How do I use a simple bash script to restart service or a program if not running, and monitor this service by a cron job in Linux.

Monitor and Restart Service If Not Running

If you want to ensure that the important server process (HTTPD/MySQLD/PHP-FPM) remain online as much as possible, and you can create a simple bash script to check if that process is running, and if it is not, restart it by executing this script. So you need to use cron to schedule this bash to be executed on a regular basis.

For example, we want to monitor and restart mysqld service in your Linux server, you can use the following bash script called


pgrep mysqld
if [ $? -ne 0 ]
    /etc/init.d/mysqld start > /dev/null 

Once you have saved the script, you need to give it executable permissions to be able to run it. Type the following command:

# chmod u+x

You can also use the another version to check multiple processes, such as: httpd, mysql, just see below script:

PLIST="httpd mysqld"
for p in $PLIST
    pgrep $p 
    if [ $? -ne 0 ]
        /etc/init.d/$p start >/dev/null
        # systemctl restart $p (For CentOS 7/RHEL7)

You can add your process list into the PLIST variable.

Add Script to Cron Job

You need to setup the cron job to restart process, and the cron tool allows you to schedule at what intervals the bash script should be executed in your server. type the following command to configure the cron file:

# crontab -e

Append the following line:

*/6 * * * * /root/ # the script will be run every six minutes

then Save and close the file.

After you set up this bash script, it will keep the process starting up after it is not running or dead for any reason. So I will ensure that the longest time that a process will be dead is for the interval of time that you specified in the cron job.

Leave a Reply
