Close

2023-08-16

Creating Hourly Event In MySQL

Creating Hourly Event In MySQL

To create an hourly event in MySQL, you must have the EVENT privilege for the database.

  1. Enable Event Scheduler:
    First, you must ensure that the event scheduler is enabled in your MySQL server. You can enable it by running the following command:
   SET GLOBAL event_scheduler = ON;

To check if the event scheduler is enabled, run the following:

   SHOW VARIABLES LIKE 'event_scheduler';
  1. Create the Event:
    Next, you can create an event that runs on an hourly basis. Here is the syntax for creating an event:
   CREATE EVENT event_name
   ON SCHEDULE EVERY 1 HOUR
   STARTS start_datetime
   DO
   BEGIN
     -- Your SQL statements here
   END;
  • event_name Is the name you want to give to the event.
  • start_datetime is the datetime when you want the event to start running. It should be in the format ‘YYYY-MM-DD HH:MM:SS’.
  • Replace -- Your SQL statements here with the SQL statements that you want to run on an hourly basis. For example, if you want to create an event named hourly_cleanup that deletes records older than 30 days from a table named logs, starting from ‘2023-08-16 00:00:00’, the SQL would look like this:
   CREATE EVENT hourly_cleanup
   ON SCHEDULE EVERY 1 HOUR
   STARTS '2023-08-16 00:00:00'
   DO
   BEGIN
     DELETE FROM logs WHERE created_at < NOW() - INTERVAL 30 DAY;
   END;
  1. Verify the Event:
    After creating the event, you can verify that it was created successfully by querying the events table in the information_schema database:
   SELECT * FROM information_schema.events WHERE event_name = 'hourly_cleanup';
  1. Alter the Event (if needed):
    You can use the statement if you need to modify the event after it has been created. For example, to change the schedule of the hourly_cleanup event to run every 2 hours, you would run:
   ALTER EVENT hourly_cleanup
   ON SCHEDULE EVERY 2 HOUR;
  1. Drop the Event (if needed):
    If you no longer need the event, you can drop it using the DROP EVENT statement:
   DROP EVENT IF EXISTS hourly_cleanup;

Please note that the MySQL event scheduler is a background process that runs scheduled events based on their schedule. Ensure your MySQL user has the necessary privileges to create and manage events.

Also, be cautious when creating events, especially those that modify data, as they can run automatically without further intervention.