MySQL Event Scheduler is a built-in scheduling tool that enables the execution of events (i.e., SQL statements or a set of SQL statements) at specific times or on a periodic basis. This facilitates more automated database management, such as regularly cleaning logs, updating statistics, or backing up data.
To utilize MySQL Event Scheduler, first ensure the event scheduler is enabled. You can verify its status with the following command:
sqlSHOW VARIABLES LIKE 'event_scheduler';
If the event scheduler is not active, enable it using:
sqlSET GLOBAL event_scheduler = ON;
Creating a scheduled event is achieved via the CREATE EVENT statement. Below is an example that truncates a table named logs at midnight every day:
sqlCREATE EVENT IF NOT EXISTS clear_logs ON SCHEDULE EVERY 1 DAY STARTS (TIMESTAMP(CURRENT_DATE, '00:00:00') + INTERVAL 1 DAY) DO TRUNCATE TABLE logs;
In this example:
IF NOT EXISTSis optional and prevents errors when creating an event with the same name if it already exists.ON SCHEDULEdefines the execution frequency; here, it is configured to run daily.STARTSspecifies the initial execution time; here, it is set to begin at midnight of the current date.DOis followed by the SQL statement to execute, which in this case is truncating thelogstable.
Additionally, you can modify existing events using ALTER EVENT or delete events with DROP EVENT. To view all current events, use:
sqlSHOW EVENTS;
By effectively leveraging MySQL Event Scheduler, you can significantly improve database management efficiency and performance.