How can I stop a MySQL query if it takes too long?

后端 未结 9 1524
野趣味
野趣味 2020-12-02 09:22

Is it possible to timeout a query in MySQL?

That is, if any query exceeds the time I specify, it will be killed by MySQL and it will return an error instead of waiti

9条回答
  •  独厮守ぢ
    2020-12-02 09:54

    I just set up the following bash script as a cron job to accomplish this with MySQL 5.0 (kills any query that has been executing for more than 30 seconds). Sharing it here in case it proves useful to anyone (apologies if my bash scripting style is inefficient or atrocious, it is not my primary development language):

    #!/bin/bash
    linecount=0
    processes=$(echo "show processlist" | mysql -uroot -ppassword)
    oldIfs=$IFS
    IFS='
    '
    echo "Checking for slow MySQL queries..."
    for line in $processes
    do
        if [ "$linecount" -gt 0 ]
            then
                pid=$(echo "$line" | cut -f1)
                length=$(echo "$line" | cut -f6)
                query=$(echo "$line" | cut -f8)
                #Id User    Host    db  Command Time    State   Info
                if [ "$length" -gt 30 ]
                    then
                        #echo "$pid = $length"
                        echo "WARNING:  Killing query with pid=$pid with total execution time of $length seconds! (query=$query)"
                        killoutput=$(echo "kill query $pid" | mysql -uroot -ppassword)
                        echo "Result of killing $pid:  $killoutput"
                fi
        fi
        linecount=`expr $linecount + 1`
    done
    IFS=$oldIfs
    

提交回复
热议问题