mysql event mechanism - regular tasks

Timing task is nothing new, because we always need to regularly modify specific data.

It's definitely a method to achieve more than one, but I always use program code to do it for a long period of time, and today suddenly thought, "Why must invoke the use of?", With the ability to implement the database itself is not better Why?

By understanding the mechanism mysql event can be timed to complete the task, the principle is to call the stored procedure specified in the specified time. Now it is not easy? Open out.

First, we need a stored procedure, although very simple, but taking into account the entry children's shoes, I posted an example:

delimiter $$;
create procedure del_car_viol()
begin
    delete from car_viol where `create` < date_sub(curdate(), interval 1 day);
end
$$;
delimiter;

This section creates a stored procedure code, it can be removed in less than yesterday's data (field names indicate please ignore).

The next step is to create an event, so the event according to certain rules to call a stored procedure, so that you can realize the function timing of the operation.

code show as below:

create event `e_update_user_ticket`  
on schedule every 1 day starts '2017-09-02 00:00:00'  
on completion not preserve enable do call del_car_viol();

Event code created above, it can be from at 0:02 on September 2017 onwards every written one day before automatically calling the stored procedure.

1 day represents the code once a day, you can replace 2 year (2 years).

After the events created will be executed once immediately, and are generally enabled by default.

 

If you do not have a stored procedure can be as follows:

DROP EVENT IF EXISTS e_update_user_ticket;
 
CREATE EVENT e_update_user_ticket
on schedule EVERY 1 DAY STARTS date_add(date( ADDDATE(curdate(),1)),interval 3 hour)  
do delete from car_viol where `create` < date_sub(curdate(), interval 1 day);

If you want to control the operational status of an event, it can be:

/*开启事件*/
alter event 事件名 on completion preserve enable; 
/*关闭事件*/
alter event 事件名 on completion preserve disable;  

If you do not know your mysql there is no time to turn on the function of support, you can query the following statement:

/*查看事件功能是否开启*/
show variables like 'event_scheduler';

Lookup table value is representative of shut off, on behalf of the open. If you want to open the event function, execute the following statement:

/*开启事件功能*/
set global event_scheduler = on;

Note that, event release mechanism is mysql5.1 been introduced, which means that version may not be lower than 5.1.

Guess you like

Origin blog.csdn.net/weixin_42656571/article/details/90172052