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

后端 未结 9 1335
野趣味
野趣味 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:57

    I think this old question needs an updated answer.

    You can set a GLOBAL timeout for all your read-only SELECT queries like this:

    SET GLOBAL MAX_EXECUTION_TIME=1000;

    The time specified is in milliseconds.

    If you want the timeout only for a specific query, you can set it inline like this:

    SELECT /*+ MAX_EXECUTION_TIME(1000) */ my_column FROM my_table WHERE ...

    MySQL returns an error instead of waiting for eternity.

    Note that this method only works for read-only SELECTs. If a SELECT statement is determined not to be read-only, then any timer set for it is cancelled and the following NOTE message is reported to the user:

    Note 1908 Select is not a read only statement, disabling timer

    For statements with subqueries, it limits the top SELECT only. It does not apply to SELECT statements within stored programs. Using the MAX_EXECUTION_TIME hint in SELECT statements within a stored program will be ignored.

    0 讨论(0)
  • 2020-12-02 10:02

    Here is my script :

    mysql -e 'show processlist\G' |\
    egrep -b5 'Time: [6-9]{3,10}' |\
    grep 'Id:' |\
    cut -d':' -f2 |\
    grep -v '155' |\ ## Binary Log PID
    sed 's/^ //' |\
    while read id
    do
        mysql -e "kill $id;"
    done
    
    0 讨论(0)
  • 2020-12-02 10:04

    Starting with MySQL 5.1 you can create a stored procedure to query the information_schmea.PROCESSLIST table for all queries that match your criteria for "long running" then iterate over a cursor to kill them. Then setup that procedure to execute on a recurring basis in the event scheduler.

    See: http://forge.mysql.com/tools/tool.php?id=106

    0 讨论(0)
提交回复
热议问题