Detailed explanation of MySQL database Event timing execution task

  • 2021-09-20 21:42:25
  • OfStack

1. Background

Because the business of the project is constantly running forward, it is inevitable that the amount of tables in the database will become larger and larger, and it will constantly occupy the hard disk space. No matter how big the space is, it can't support the growth of business, so it is necessary to delete unnecessary data regularly. In our project, because we don't clean up the data, one table takes up as much space as 4G. Think about how horrible it is...

What is introduced here is to use MySQL to establish a timer Event to regularly clear away unnecessary events before.

2. Content


#1 Creates a stored procedure for the event to call 
delimiter//
drop procedure if exists middle_proce//
create procedure middle_proce()
begin
DELETE FROM jg_bj_comit_log WHERE comit_time < SUBDATE(NOW(),INTERVAL 2 MONTH);
optimize table jg_bj_comit_log;
DELETE FROM jg_bj_order_create WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_order_create;
DELETE FROM jg_bj_order_match WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_order_match;
DELETE FROM jg_bj_order_cancel WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_order_cancel;
DELETE FROM jg_bj_operate_arrive WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_operate_arrive;
DELETE FROM jg_bj_operate_depart WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_operate_depart;
DELETE FROM jg_bj_operate_login WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_operate_login;
DELETE FROM jg_bj_operate_logout WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_operate_logout;
DELETE FROM jg_bj_operate_pay WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_operate_pay;
DELETE FROM jg_bj_position_driver WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_position_driver;
DELETE FROM jg_bj_position_vehicle WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_position_vehicle;
DELETE FROM jg_bj_rated_passenger WHERE created_on < SUBDATE(NOW(),INTERVAL 3 MONTH);
optimize table jg_bj_rated_passenger;
end//
delimiter;

#2 , open event( To make timing work, MySQL Constants of GlOBAL event_schduleer  Must be on  Or 1)
show variables like 'event_scheduler'
set global event_scheduler='on'

#3 , creating Evnet Events 
drop event if exists middle_event;
create event middle_event
on schedule every 1 DAY STARTS '2017-12-05 00:00:01'
on completion preserve ENABLE
do call middle_proce();

#4 , open Event  Events 
alter event middle_event on completion preserve enable;

#5 , close Event  Events 
alter event middle_event on completion preserve disable;

Related articles: