← Back to Chapters

MySQL Event Scheduler

⏰ MySQL Event Scheduler

? Quick Overview

The MySQL Event Scheduler allows you to run SQL statements automatically at scheduled times, similar to a cron job inside the database.

? Key Concepts

  • Events run automatically without user interaction
  • Scheduler must be enabled globally
  • Events can run once or repeatedly
  • Useful for cleanup, archiving, and automation

? Syntax / Theory

An event is created using CREATE EVENT and scheduled using AT or EVERY.

? View Code Example
// Enable the global event scheduler
SET GLOBAL event_scheduler = ON;

? Code Example(s)

? View Code Example
// 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;
? View Code Example
// 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;

? Live Output / Explanation

MySQL executes these events automatically at the scheduled time without manual execution.

? Interactive Simulator

This JavaScript demo simulates how MySQL event scheduling behaves.

> Scheduler initialized...

? Tips & Best Practices

  • Check scheduler status before creating events
  • Use events for lightweight tasks
  • Monitor using SHOW EVENTS
  • Schedule heavy tasks off-peak

? Try It Yourself

  • Create an hourly logging event
  • Disable and re-enable an event
  • List all events in your database