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 monitorP.sh:
#!/bin/bash pgrep mysqld if [ $? -ne 0 ] then /etc/init.d/mysqld start > /dev/null fi
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 monitorP.sh
You can also use the another version to check multiple processes, such as: httpd, mysql, just see below script:
#!/bin/bash PLIST="httpd mysqld" for p in $PLIST do pgrep $p if [ $? -ne 0 ] then /etc/init.d/$p start >/dev/null # systemctl restart $p (For CentOS 7/RHEL7) done
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/monitorP.sh # the script will be run every six minutes
then Save and close the file.