Creating Hourly Event In MySQL
To create an hourly event in MySQL, you must have the EVENT privilege for the database.
- 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';
- 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 namedhourly_cleanup
that deletes records older than 30 days from a table namedlogs
, 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;
- Verify the Event:
After creating the event, you can verify that it was created successfully by querying theevents
table in theinformation_schema
database:
SELECT * FROM information_schema.events WHERE event_name = 'hourly_cleanup';
- 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 thehourly_cleanup
event to run every 2 hours, you would run:
ALTER EVENT hourly_cleanup
ON SCHEDULE EVERY 2 HOUR;
- Drop the Event (if needed):
If you no longer need the event, you can drop it using theDROP 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.