Event Scheduler or Setting Timers in MySQL
This tutorial will guide you through creating a MySQL EVENT
timer, also known as a MySQL timer.
We will see how to set a timer in MySQL to let MySQL manipulate the data (eg. UPDATE
// data) INSERT
. DELETE
It will also take a backup (if required) at the mentioned date and time.
We will study MySQL considering different scenarios EVENT
. Also, discuss its importance and benefits. For this article, we are using MySQL version 8.0.27, but you can get the newer version (if available) from their official website.
MySQL 事件
and its importance
MySQL EVENT
is used to schedule tasks for certain operations - for example, updating a column, fetching a table, or taking a database backup.
You can 创建``事件
have it executed only once or repeatedly at a given interval - for example, every minute, hour, month or year.
There is no fixed number of statements to create EVENT
. EVENT
There can be many lines in the body.
If EVENT
the has more than one line, the body must be contained in BEGIN
and END
blocks. It is also important to know that scheduled EVENT
commands are stored in and executed 数据库
in the scheduled 日期
and .时间
Creating events is important for the following benefits:
- Get Everyone on the Same Page
- Set your goals
- Manage schedules and execute events
- Used to optimize tables and update data
- Generate useful reports for off-peak hours
- Lets you prioritize your tasks
- Save your money and time
Event
Scheduling a program or setting a timer in MySQL
Delays are very costly to both production teams and brands.
Scheduling 事件
or setting timers for specific fields (columns) and then dumping them into separate files for project reports will save their time. This way, it will let them focus on other productive tasks.
MySQL uses a single event_scheduler
thread named to execute all events. If event_scheduler
the value of is ON
, then EVENT
is executed; otherwise, it is not.
You have to event_scheduler
set the value of to using the following command ON
.
SET GLOBAL event_scheduler = ON;
Now, if you 创建
one 事件
, how do you know it will be executed? Use the following command to see.
SHOW PROCESSLIST;
Let's look at the output before and after event_scheduler
setting the value of to .ON
In the first output, you cannot execute EVENT
, but in the second output, you can. This is because the second screenshot event_scheduler
has ON
.
Output:
You can 创建``事件
use it for different purposes - for example, 事件
to run it only once or once a year, or at a given interval. Let's start understanding with the help of sample code.
We person
have a table in database student
which has the following records at current time.
Let's take a look at one-time events. The sample code is as follows 创建
.事件
SET GLOBAL event_scheduler = ON;
CREATE EVENT IF NOT EXISTS ONE_TIME_EVENT
ON SCHEDULE AT CURRENT_TIMESTAMP
DO
INSERT INTO person.student (id, FIRST_NAME, LAST_NAME, GENDER, EMAIL)
VALUES
(7, 'Thomas', 'Christoper', 'Male', 'tchristopher@gmail.com');
In the code given above, we event_scheduler
set the value of ON
to execute EVENT
.
We then created one EVENT
, named it ONE_TIME_EVENT
, and scheduled it on CURRENT_TIMESTAMP
. This EVENT
means it will CURRENT_TIMESTAMP
execute once on and then expire.
This is created only if it does not exist EVENT
. This EVENT
job is a row INSERT
in student
the table.
After creating and executing this EVENT
, check student
the table to see the new record (see the following screenshot).
Output:
Suppose you need 创建
an event that will CURRENT_TIMESTAMP
be executed 20 seconds after 事件
. This event will only be executed once. Write the following code to understand.
CREATE EVENT IF NOT EXISTS ONE_TIME_EVENT_WITH_INTERVAL
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 20 SECOND
DO
INSERT INTO person.student
VALUES
(8, 'Suzu', 'Aly', 'Fmale', 'aly.suzu@yahoo.com');
Output:
student
You can see the new record in the table after 20 seconds .
Remember, if you check it before 20 seconds have passed, you won't student
see this new row in the table. Let the twenty seconds pass, then check.
Use the following code to see how many events are created and scheduled.
SHOW EVENTS FROM classicmodels;
Output:
Why aren't there any listed in the screenshot above EVENT
? Because all of our events are now expired, according to this post.
You can use ON COMPLETION PRESERVE
the clause to track all events, regardless of whether they are expired or not, as shown below.
CREATE EVENT TEST_PRESERVE_CLAUSE
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 MINUTE
ON COMPLETION PRESERVE
DO
INSERT INTO tests(test_name,test_date)
VALUES('Testing Preserve Clause',NOW());
What if you want 创建
an event that CURRENT_TIMESTAMP
starts at , 分钟
executes once every , and 小时
expires after . It is called a recurring event.事件
You can use the following code to create and practice.
CREATE EVENT RECURRING_EVENT
ON SCHEDULE EVERY 1 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
INSERT INTO Tests(test_name,test_date)
VALUES('This is recurring event test',NOW());
In the code given above, we use STARTS
and ENDS
to tell EVENT
the start and end time. You can also delete the event when you think that you don't need it now.
EVENT
Substitute your name in the following code name
.
DROP EVENT [IF EXIST] name;
Let's take another situation where you create EVENT
and hand over the work to another developer. Isn't it COMMENT
easy to understand? Of course not.
CREATE
EVENT
And COMMENT
practice by adding , as shown below.
CREATE EVENT RECURRING_EVENT
ON SCHEDULE EVERY 1 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
COMMENT 'It will add a new record every minture for one hour'
DO
INSERT INTO Tests(test_name,test_date)
VALUES('This is recurring event test',NOW());
We have EVENT
learned using only one line in the body EVENT
. What if you have multiple lines? Let's understand it with the following sample code.
delimiter |
CREATE EVENT IF NOT EXISTS EVENT_FOR_UPDATE_COLUMNS_AND_DUMP
ON SCHEDULE AT current_timestamp
DO BEGIN
UPDATE student SET GENDER = 'M' WHERE student.GENDER = 'Male';
UPDATE student SET GENDER = 'F' WHERE student.GENDER = 'Female';
Table student INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/file.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r\n';
END |
delimiter ;
EVENT
You'll see three queries in the body of the provided code . Whenever you EVENT
have multiple lines in the body of the , enclose them in BEGIN
and END
, as described above.
In this example, we create a CURRENT_TIMESTAMP
. EVENT
It will UPDATE
update the column based on the statement GENDER
and export the data to .CSV
a .
For export, you must use this path C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/file.csv
(if you have installed MySQL in C drive). Otherwise, you will get the following error.
Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
If you have installed MySQL somewhere else, use the EVENT scheduler and then use the following command to find the path where your files will be exported.
SHOW VARIABLES LIKE "secure_file_priv";
in conclusion
EVENT
We have learned about MySQL scheduler in this tutorial .
We learned how to create events that will execute once and only once at a provided interval. We also explored creating events with multiple rows, updating the data, and then exporting it to separate files.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
If ELSE in MySQL
Publish Date:2025/04/11 Views:85 Category:MySQL
-
In this tutorial, we aim to explore how to use IF ELSE the statement in MySQL. One of the key roles of a data analyst is to gather insights from the data and produce meaningful results. It can be done with the help of several data filtering
DATETIME vs. TIMESTAMP in MySQL
Publish Date:2025/04/11 Views:117 Category:MySQL
-
DATETIME and TIMESTAMP are two different data types that can be used to store values that must contain both a date and a time portion. In this article, we will understand how it is stored in the database and the memory required for ea
Execute multiple joins in one query in MYSQL
Publish Date:2025/04/11 Views:94 Category:MySQL
-
Have you ever wondered how to include multiple joins in one query in MySQL? You have come to the right place. Remember that joins allow us to access information from other tables. This information is included separately to avoid redundancy.
Joining 3 tables in MySQL
Publish Date:2025/04/11 Views:187 Category:MySQL
-
In this tutorial, we will learn how to join three tables in MySQL. Businesses and organizations may have to visualize three tables simultaneously based on certain matching columns common to all three tables. This operation is allowed in MyS
Use of UPDATE JOIN in MySQL
Publish Date:2025/04/11 Views:85 Category:MySQL
-
This tutorial will explain how to use the statement in MySQL database UPDATE JOIN . We generally use joins to iterate over the rows in a particular table which may or may not have similar rows in other tables. We can UPDATE use JOIN the cla
How to use the Row_Number() function in MySQL
Publish Date:2025/04/11 Views:142 Category:MySQL
-
In this tutorial, we will explain how to use the VALUES function in MySQL ROW_NUMBER() . This is a sorting method that assigns consecutive numbers within a partition starting from 1. It is important to note that no two rows within a partiti
Multiple primary keys in MySQL
Publish Date:2025/04/11 Views:66 Category:MySQL
-
In this tutorial, our goal is to explore the concept of multiple primary keys for a table in MySQL. Many times, businesses and organizations have to assign certain columns as primary keys. This primary key has multiple uses and reasons to b
Displaying foreign keys in MySQL
Publish Date:2025/04/11 Views:55 Category:MySQL
-
In this tutorial, we aim to explore how to display foreign keys for tables and columns in MySQL. The type of key that references a primary key, also known as the primary key of another table, is called a foreign key. Understanding the forei
Select first N rows in MySQL
Publish Date:2025/04/11 Views:85 Category:MySQL
-
Sometimes, you have to select first N rows of MySQL database according to your project requirements. n The value of varies according to the requirement; it can be TOP 1 row or TOP 30 rows. We will learn how to select top N rows using the cl