mysql定时任务event——清理过期数据

时间:2022-02-24 07:02:14

需要删除数据的表名:t_req_log

建表sql

CREATE TABLE `t_req_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`host` varchar(200) DEFAULT NULL,
`time` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1.查询是否开启事件调度

SHOW VARIABLES LIKE 'event_scheduler';

2.开启事件调度

临时:
SET GLOBAL event_scheduler = 1;

永久:
vim /etc/my.cnf
event_scheduler=ON

3.创建p_del_count存储过程。
接收传入参数30并执行删除数据操作,删除大于30天的数据。

drop procedure if exists p_del_count;
create procedure p_del_count(IN `date_inter` INT)
BEGIN
delete from t_req_log where (TO_DAYS(NOW()) - TO_DAYS(FROM_UNIXTIME(unix_timestamp(time),'%Y%m%d'))) >=date_inter;
END;

4.创建定时任务
从2018-05-15 00:00:00起每一天执行一次p_del_count这个存储过程,并将参数传给

p_del_count存储过程

drop event if exists e_del_t_req_log;
create event e_del_t_req_log
on schedule every 1 day starts '2018-05-15 00:00:00'
on completion not preserve enable do call p_del_count (30);

5.查看已有定时事件任务
SHOW EVENTS;

6.事件的开启与关闭
开启某事件:ALTER EVENT e_del_t_req_log ON COMPLETION PRESERVE ENABLE;
关闭某事件:ALTER EVENT e_del_t_req_log ON COMPLETION PRESERVE DISABLE;