欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL数据库Event定时执行任务详解

程序员文章站 2022-04-08 15:42:35
一、背景   由于项目的业务是不断往前跑的,所以难免数据库的表的量会越来越庞大,不断的挤占硬盘空间。即使再大的空间也支撑不起业务的增长,所以定期删除不必要的数据...

一、背景

  由于项目的业务是不断往前跑的,所以难免数据库的表的量会越来越庞大,不断的挤占硬盘空间。即使再大的空间也支撑不起业务的增长,所以定期删除不必要的数据是很有必要的。在我们项目中由于不清理数据,一个表占的空间竟然达到了4g之多。想想有多可怕...

  这里介绍的是用mysql 建立一个定时器event,定期清除掉之前的不必要事件。

二、内容

#1、建立存储过程供事件调用
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、开启event(要使定时起作用,mysql的常量global event_schduleer 必须为on 或者1)
show variables like 'event_scheduler'
set global event_scheduler='on'

#3、创建evnet事件
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、开启event 事件
alter event middle_event on completion preserve enable;

#5、关闭event 事件
alter event middle_event on completion preserve disable;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。