Last active
March 2, 2020 15:49
-
-
Save sc0ttdav3y/2af9aa1078884b24a4190d04ca5e8b09 to your computer and use it in GitHub Desktop.
Kill Slow Running MySQL Queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | |
-- Kills long running queries | |
-- | |
-- @see https://stackoverflow.com/a/27293134 | |
-- | |
DROP PROCEDURE IF EXISTS `KillLongRunningQueries`; | |
SET GLOBAL event_scheduler = ON; | |
-- | |
-- SP: KillLongRunningQueries() | |
-- | |
-- Checks for any queries that have been running for > 300 seconds. | |
-- If any are found, they are killed using KILL QUERY. | |
-- | |
DELIMITER // | |
CREATE PROCEDURE KillLongRunningQueries () | |
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// | |
-- | |
-- EVENT: KillLongRunningQueries | |
-- | |
-- Schedules KillLongRunningQueries() to run every 60 seconds | |
-- | |
DELIMITER ; | |
CREATE EVENT KillLongRunningQueries | |
ON SCHEDULE EVERY 60 SECOND | |
DO CALL KillLongRunningQueries(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment