Use Linux's Shell script to handle MySQL timeouts

  • 2020-06-01 11:12:12
  • OfStack

Recently, I just joined a new company and took over a site here. Due to the unreasonable architectural design of this site, MySQL was always under great pressure, and the Locked process often ran out of time. Therefore, I wrote a paragraph of Linux's Shell script to regularly delete these processes by kill.
The script is as follows:

#!/bin/bash 
mysql_pwd="xxxxxx" #mysql the root password  
mysql_exec="/usr/local/mysql/bin/mysql"
tmp_dir="/tmp"
file_sh="$tmp_dir/mysql_kill_locked.sh"
file_tmp="$tmp_dir/mysql_kill_locked.tmp"
file_log="$tmp_dir/mysql_kill_locked.log" # The log  
$mysql_exec -uroot -p$mysql_pwd -e "show processlist" | grep -i "Locked" > $file_tmp 
cat $file_tmp >> $file_log 
for line in `cat $file_tmp | awk '{print $1}'` 
do
echo "$mysql_exec -uroot -p$mysql_pwd -e "kill $line"" >> $file_sh 
done
chmod +x $file_sh 
sh $file_sh # Execute temporary script  
> $file_sh # Empty the temporary script 
 

Finally, add the script to crontab and execute it on a regular basis.

Related articles: