MySQL process check with cron

Posted May 26, 2015 9.2k views
Linux Basics

I can run this script fine from the terminal and I get the else but when I have cron set to run it every 5 minutes I am sent a email and the mysql server is restarted every 5 minutes. So I am guessing that the cron job does not have the correct permission to see if the process is running, so it restarts the server and sends an email. How would I get this script to execute from cron and be able to check if mysql process is running?

UP=$(service mysql status | grep 'mysql start/running' | wc -l);
if [ "$UP" -ne 1 ];
        sudo service mysql start
        cat /var/db-backup/mysql_restart_email | msmtp
        echo "All is well.";

  • When you added your script to your crontab did you do a crontab -e as the root user? If you did then the script should be running with root privileges and permissions would not be the issue.

  • It works great when I execute it from the terminal with ./

    When mysql is stopped:
    mysql stop/waiting

    When mysql is running:
    mysql start/running, process 2554

  • I should also note that if your MySQL process is crashing regularly that you should consider taking other measures as this will eventually result in your data being corrupted and the service possibly not being able to start at all. The most common reason for MySQL to be crashing is running out of memory. Creating a swap file can provide a useful stopgap against this occurring but for the best performance you may want to consider upgrading to a larger droplet.

    by Justin Ellingwood
    Swap space can be used as an "overflow" area for your system when you run out of RAM. The operating system can store data that would normally be kept in RAM on the hard drive in a specially formatted file. In this guide, we'll demonstrate how to create and use one of these files in Ubuntu 14.04.
  • I do have a swap file and It does not crash that often maybe once a month, but I have a client that is annoying and cheap and if it does hes contacting me left and right.

    Yes it was added while logged in as root

  • Show 1 more comments

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
2 answers

Here is my take on the same idea, but I made it so the script checks on other services (like Apache2)

works fine on all my DO droplets for the last several months.

when you set up the cronjob, are you running:

sudo crontab -e