MySQL Event Management
MySQL Events are scheduled tasks that run automatically at defined times or intervals. They are ideal for automating repetitive operations such as data cleanup, reporting, or maintenance. Before creating events, ensure the event scheduler is enabled and you have the required privileges.
1. Enabling the Event Scheduler
Turn the event scheduler on (requires SUPER or appropriate privileges):
SET GLOBAL event_scheduler = ON;
Verify scheduler status:
SHOW VARIABLES LIKE 'event_scheduler';
Note: To enable the scheduler permanently across server restarts, set event_scheduler=ON in your MySQL configuration (e.g., my.cnf).
2. Creating a One-Time Event
Schedule an event to run once at a specified time:
Syntax:
CREATE EVENT event_name
ON SCHEDULE AT timestamp
DO
-- statement(s) to run;
Example (runs once one hour from now):
CREATE EVENT delete_old_logs
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
DELETE FROM logs WHERE log_time < NOW() - INTERVAL 30 DAY;
3. Creating a Recurring Event
Schedule an event to run repeatedly at fixed intervals:
Syntax:
CREATE EVENT event_name
ON SCHEDULE EVERY interval
DO
-- statement(s) to run;
Example (daily cleanup):
CREATE EVENT daily_cleanup
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM sessions WHERE last_active < NOW() - INTERVAL 1 DAY;
4. Modifying an Event
Change an event’s schedule or body with ALTER EVENT:
Syntax:
ALTER EVENT event_name
ON SCHEDULE ...
[DO ...];
Example (change schedule):
ALTER EVENT daily_cleanup
ON SCHEDULE EVERY 1 WEEK;
5. Dropping an Event
Remove an event permanently:
Syntax:
DROP EVENT event_name;
Example:
DROP EVENT delete_old_logs;
6. Viewing Events
To list all events in the current database:
SHOW EVENTS;
To view the full definition (SQL) of a specific event:
SHOW CREATE EVENT event_name;
Example:
SHOW CREATE EVENT daily_cleanup;
Notes & Tips
- You need the
EVENTprivilege to create, alter, or drop events in a given schema. - Events execute with the privileges of their
DEFINERaccount by default—be mindful of security. - Event status can be
ENABLEDorDISABLED. UseALTER EVENT ... ENABLE|DISABLEto change it. - For persistent scheduling across restarts, set
event_scheduler=ONin the server configuration file.