The MySQL Event Scheduler allows you to run SQL statements automatically at scheduled times, similar to a cron job inside the database.
An event is created using CREATE EVENT and scheduled using AT or EVERY.
// Enable the global event scheduler
SET GLOBAL event_scheduler = ON;
// One-time scheduled event
CREATE EVENT delete_old_logs
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO
DELETE FROM logs WHERE created_at < NOW() - INTERVAL 30 DAY;
// Daily recurring scheduled event
CREATE EVENT daily_cleanup
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_TIMESTAMP
DO
DELETE FROM sessions WHERE last_active < NOW() - INTERVAL 7 DAY;
MySQL executes these events automatically at the scheduled time without manual execution.
This JavaScript demo simulates how MySQL event scheduling behaves.
SHOW EVENTS