Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active August 25, 2017 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/f05f936c85d3f4cff7265ee688e01ae8 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/f05f936c85d3f4cff7265ee688e01ae8 to your computer and use it in GitHub Desktop.
Parameterise GET_LOCK based on Database Schema #mysql
-- when creating events on MySQL,
-- you probably don't want the events to run simultaneously
-- if the execution of a event takes too long
-- this shows you to use GET_LOCK and RELEASE_LOCK with events
-- note that GET_LOCK and RELEASE_LOCK unlike many other MySQL commands
-- do not automatically namespace themselves within the currently used database
-- so we have to use this CONCAT_WS technique
-- note that unlike cron, mysql events when scheduled as recurring without a designated start date
-- will immediately execute upon creation
-- you can confirm this with SELECT * FROM information_schema.events\G
USE exampleDatabase;
DROP EVENT IF EXISTS exampleEvent;
DELIMITER //
CREATE EVENT exampleEvent
ON SCHEDULE EVERY 1 SECOND
DO BEGIN
IF (SELECT GET_LOCK(CONCAT_WS('.', DATABASE(), 'exampleEvent'), 0)) THEN
-- do something here...
SELECT RELEASE_LOCK(CONCAT_WS('.', DATABASE(), 'exampleEvent'));
END IF;
END //
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment