Put this code into a .sh file, add executable permissions to it and add it to root user’s crontab.

See also: Restart MySQL automaticaly