Anyway to Limit MySQL Query Execution time?

前端 未结 4 1911
旧时难觅i
旧时难觅i 2020-12-06 20:10

Hi I\'m having issues on my server at the minute because some of the MySQL queries are taking a very long time to run, and hogging the resources on the server.

I\'m

相关标签:
4条回答
  • 2020-12-06 20:27

    There is no way to do it using MySQL options. But you can still do it using daemon process as @rabudde advised.

    In this case, if you kill process you will abort transaction and it will be rollback.

    0 讨论(0)
  • 2020-12-06 20:35

    I can recommend http://www.percona.com/doc/percona-toolkit/2.1/pt-kill.html which is designed specifically for that. From man page:

    pt-kill - Kill MySQL queries that match certain criteria.
    
    0 讨论(0)
  • 2020-12-06 20:43

    This is a purely php solution that seems to be the simplest solution from what I've managed to find so far.

    $result = mysql_query("SHOW FULL PROCESSLIST");
    while ($row=mysql_fetch_array($result)) 
    {
      $process_id = $row["Id"];
      if ($row["Time"] > 200 ) 
      {
        $sql="KILL {$process_id}";
        mysql_query($sql);
      }
    }
    

    And running this from a CRON script every 60 seconds.

    If anyone does find a better solution to this issue please let me know

    0 讨论(0)
  • 2020-12-06 20:46

    you can use the following procedure to check for queries running longer than 300secs. the event runs the procedure periodically and kills all long running queries.

        CREATE PROCEDURE DBNAME.kill_long_running_queries ()
    BEGIN
    
      DECLARE v_qid BIGINT;
      DECLARE v_finished INT DEFAULT 0;
      DECLARE c_queries CURSOR FOR SELECT ID FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND = 'Query' AND TIME > 300;
      DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
    
      OPEN c_queries;
    
      l_fetch_queries: LOOP
        FETCH c_queries INTO v_qid;
        IF v_qid > 0 THEN
          KILL QUERY v_qid;
        END IF;
        IF v_finished THEN
          LEAVE l_fetch_queries;
        END IF;
      END LOOP l_fetch_queries;
      CLOSE c_queries;
    
    END
    
    CREATE EVENT kill_long_running_queries
    ON SCHEDULE EVERY 60 SECOND
    DO CALL DBNAME.kill_long_running_queries();
    
    0 讨论(0)
提交回复
热议问题