MySQL: Brief Introduction to MySQL Event Scheduler
By: Shubham Kaushik
Tags: Startup, Software Development, Life, Technology, Database

Prerequisite

MySQL installed on your machine Background on MySQL Database The ability to simplify is always a plus 😃

What is MySQL Event Scheduler?

The MySQL Event Scheduler is a tool that manages the scheduling and execution of events that are so-called tasks that run according to a schedule. MySQL introduced the Event Scheduler in version 5.1.6. When we create an event then, actually we are creating a named database object containing one or more SQL statements to be executed at one or more regular intervals, beginning and ending at a specific date and time. The idea of this event scheduler is similar to the idea of the Unix crontab (also knows as a “cronjob”) or the Windows Task Scheduler.

When to use MySQL Event Scheduler?

Suppose you manage your database which consists of two tables. One table consists of the data related to user's information like Name, Age, DOB, Gender, etc. and in the other table, we want to enter the data only once a day in which we push the number of user entries created for each day.

Now at first, this problem statement looks easy to you! Let's first go with the cronjob approach. We can write one script which will fetch all the user entries created for each day and insert the result into another table. And we will execute our script using cronjob by setting the scheduled time using crontab expression.

But wait! Let's re-iterate over the approach once.

We have to write the block of code which will handle our business logic.

Then, we need to add a cronjob which will trigger our script with a specific interval.

Now we are consuming two machines here, the one in the database and the other is the machine where we are setting up our cronjob.

Don’t you think it's a wastage of resources? Can we do it using the single machine? Say thanks to MySQL Task scheduler!

We can use MySQL Event Scheduler when our task is purely data-centric or complements the functionality that is already built into the database. We can do data clean-up, log certain events, aggregate certain data, etc using this event scheduler.

MySQL Event Scheduler over CronJob

There are a few use-cases where we can prefer MySQL Event scheduler over Cronjob. But we cannot make a decision based on these use-cases and make a statement about which is the best. The following are the advantages if we use MySQL Event Scheduler:

It is directly written in MySQL Server.

It is the platform-independent approach. So if our application is written in any language it does not matter we just need to know MySQL.

Whenever there is a database update or cleanup required at regular intervals we can using this event scheduler approach.

There is no need to compile queries every time so it improves the performance.

MySQL Event Scheduler Configuration

MySQL uses a special thread called the event scheduler thread to execute all scheduled events. We can view the status of the event scheduler thread by executing the below command:

SHOW PROCESSLIST;

If the event scheduler is not enabled, we can set the event scheduler system variable to enable and start it using the below command:

SET GLOBAL event_scheduler = ON;

Now if we Execute the first command we can see the state of the event scheduler thread:

Creating New MySQL Events Syntax

Let's create our first MySQL event using the below basic syntax:

CREATE EVENT [IF NOT EXIST] event_name

ON SCHEDULE schedule

DO event_body

In this syntax:

First, we specify the name of the event that we want to create with “CREATE EVENT” keywords. The event names must be unique within the same database. Second, specify a schedule after the “ON SCHEDULE” keywords.

If the event is a one-time event, we use the below syntax:

AT timestamp [+ INTERVAL]

If the event is a recurring event, we use the EVERY clause:

EVERY interval STARTS timestamp [+INTERVAL] ENDS timestamp [+INTERVAL]

Third, place SQL statements after the DO keyword. And we can call a stored procedure inside the body of an event. In case we have compound statements, we can wrap them in a “BEGIN END” block.

Implementing MySQL Event for our Use-Case

Let’s create a table that consists of user’s information like Name, Age, Gender, DOB using the below command:

CREATE TABLE USERS (

id INT PRIMARY KEY AUTO_INCREMENT,

Name VARCHAR(20) NOT NULL,

Gender VARCHAR(1) NOT NULL,

AGE INT NOT NULL,

CREATED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

UPDATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

);

Now we will create another table that will store the count of user entries for each day and create this table using the below command:

CREATE TABLE USERS_COUNT_DAY_WISE (

id INT PRIMARY KEY AUTO_INCREMENT,

USER_ENTRIES_ON DATETIME,

COUNT INT

);

Here comes the time for our MySQL Event Scheduler. We will create an event that fetches the number of user entries for each day from the “USERS” table and insert the result into the “USERS_COUNT_DAY_WISE” table. And we will execute this task once a day. Using the below command we can create this event and schedule it for a specific time interval:

CREATE EVENT USERS_ENTRY_COUNT

ON SCHEDULE EVERY 1 DAY

STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)

DO

INSERT INTO USERS_COUNT_DAY_WISE (USER_ENTRIES_ON, COUNT) SELECT NOW(), COUNT(*) FROM USERS WHERE CREATED_AT >= DATE_SUB(NOW(), INTERVAL 1 DAY);

To check our executed event, we can use the below command:

SELECT event_schema, event_definition, status, starts, last_executed FROM INFORMATION_SCHEMA.EVENTS

Greetings! 🥳

We have successfully created our first MySQL Event which will take care of a specific task and we also envoke this task for a specific interval of time.

As a Page of victory let's check if our scheduled event is added to the process list or not.