RianAcademy
Search
⌘
K
Premium

Event Scheduler

In real-world applications, there's often a need to automatically execute certain actions on a schedule: cleaning up old records, updating statistics, generating reports.

For these tasks, MySQL provides a mechanism called scheduled events.

Events in MySQL are similar to a task scheduler in an operating system: you create a task once, and the database executes it automatically on schedule.

When it is useful

Scheduled events help automate the following tasks:

  • Data cleanup: removing outdated log records or temporary data
  • Statistics updates: recalculating aggregated data for analytics
  • Report generation: automatically creating periodic reports
  • Data maintenance: moving records to archive tables and performing other routine operations

Enabling the scheduler

Before creating events, make sure the event scheduler is enabled:

MySQL 8.4
SHOW VARIABLES LIKE 'event_scheduler';

If the scheduler is disabled, enable it:

MySQL 8.4
SET GLOBAL event_scheduler = ON;

This command changes the setting until the next server restart and requires permission to modify global system variables. To enable the scheduler permanently, use the server configuration or SET PERSIST if it is available in your MySQL version.

One-Time Execution

Let's start with the simplest case — an event that executes once at a specific time:

MySQL 8.4
CREATE EVENT cleanup_old_logs
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO
    DELETE FROM logs WHERE created_at < NOW() - INTERVAL 30 DAY;

This event will delete log records older than 30 days, 24 hours after the event is created.

Breaking down the syntax:

  • CREATE EVENT cleanup_old_logs — create an event named cleanup_old_logs
  • ON SCHEDULE AT — specify when the event should execute
  • CURRENT_TIMESTAMP + INTERVAL 1 DAY — execution time (in 1 day)
  • DO — the event body: one simple SQL statement or a BEGIN ... END compound statement

Recurring Execution

More often, events need to run periodically — every day, hour, or minute:

MySQL 8.4
CREATE EVENT update_statistics
ON SCHEDULE EVERY 1 HOUR
DO
BEGIN
    UPDATE product_stats SET
        total_sales = (SELECT SUM(amount) FROM orders WHERE product_id = product_stats.product_id),
        last_updated = NOW();
END;

This event will update sales statistics every hour.

Breaking down the syntax:

  • ON SCHEDULE EVERY 1 HOUR — execute every hour
  • BEGIN ... END — a compound statement to which you can add multiple SQL statements when needed

Interval options:

  • EVERY 1 MINUTE — every minute
  • EVERY 1 HOUR — every hour
  • EVERY 1 DAY — every day
  • EVERY 1 WEEK — every week
  • EVERY 1 MONTH — every month
  • EVERY 30 SECOND — every 30 seconds

Limiting the Execution Period

Sometimes you need an event to run only during a specific period.

MySQL 8.4
CREATE EVENT temporary_log_cleanup
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 30 DAY
DO
    DELETE FROM logs WHERE created_at < NOW() - INTERVAL 30 DAY;

This event will delete outdated logs once a day for 30 days.

New elements:

  • STARTS — start of the event's active period
  • ENDS — end of the event's active period

After ENDS, the event stops running and is dropped by default. Add ON COMPLETION PRESERVE when creating it if you want to retain its definition.

Viewing the Schedule

To see all created events:

MySQL 8.4
SHOW EVENTS;

To view events in a specific database:

MySQL 8.4
SHOW EVENTS FROM your_database_name;

Managing the Schedule

Temporarily disable an event:

MySQL 8.4
ALTER EVENT cleanup_old_logs DISABLE;

Enable an event:

MySQL 8.4
ALTER EVENT cleanup_old_logs ENABLE;

Change event schedule:

MySQL 8.4
ALTER EVENT cleanup_old_logs
ON SCHEDULE EVERY 2 HOUR;

Delete an event:

MySQL 8.4
DROP EVENT IF EXISTS cleanup_old_logs;
  1. Access privileges: Creating events requires the EVENT privilege.

  2. Time zone: MySQL interprets the schedule using the current session's time_zone when the event is created or altered and stores that time zone with the event.

  3. Overlapping runs: If an event runs longer than its interval, MySQL may start multiple instances at the same time. Use a lock or another concurrency guard when overlapping runs are not acceptable.

  4. Performance: A suitable frequency depends on the cost of the operation and the database load, not on a universal minimum interval.

Self-Check

What is the minimum interval you can use for recurring events?

Scheduled events are a powerful tool for automating routine database tasks. They help maintain data cleanliness, update statistics, and perform maintenance operations without developer intervention! 🚀