Home > Database > Mysql Tutorial > MySQL定时任务event_MySQL

MySQL定时任务event_MySQL

WBOY
Release: 2016-06-01 13:31:20
Original
921 people have browsed it

bitsCN.com

MySQL定时任务event

 

由于一些业务需求,我们可能需要定时清除数据库一些废弃的数据,可以使用mysql的存储过程和事件来完成。

 

下面例子定时清除日志表log中指定天数前的数据

 

1、创建日志表log

CREATE TABLE IF NOT EXISTS `log` (  `log_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '记录id',  `user_id` int(11) DEFAULT NULL COMMENT '用户id',  `op` varchar(128) NOT NULL COMMENT '操作类型',  `model` varchar(32) DEFAULT NULL COMMENT '操作模块',  `activity_time` int(10) NOT NULL DEFAULT '0' COMMENT '操作时间',  `data` text COMMENT '数据',  PRIMARY KEY (`log_id`)) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='用户日志表' AUTO_INCREMENT=1 ;
Copy after login

2、创建事件e_del_logs

CREATE EVENT `e_del_logs` ON SCHEDULE EVERY 1 DAY STARTS '2013-07-30 17:33:43' ON COMPLETION NOT PRESERVE ENABLE DO call p_del_logs(90);
Copy after login

//上面代码表示从2013-07-30 17:33:43起每一天执行一次p_del_logs这个存储过程,并带上参数

3、建立存储过程

p_del_logsDELIMITER $$---- 存储过程--CREATE PROCEDURE `p_del_logs`(IN `date_inter` int)BEGIN    delete from log where (to_days(now()) - to_days(FROM_UNIXTIME(activity_time)))>=date_inter;END$$DELIMITER ;
Copy after login

//按事件传过来的参数90,删除操作时间90天之前的数据

这样mysql就会定制每天去执行这个任务了。

查看当前是否已开启事件计划(调度器)有3种方法:

1)     SHOW VARIABLES LIKE 'event_scheduler';2)     SELECT @@event_scheduler;3)     SHOW PROCESSLIST;
Copy after login

(二) 开启事件计划(调度器)开关有4种方法:

1)     SET GLOBAL event_scheduler = 1;2)     SET @@global.event_scheduler = 1;3)     SET GLOBAL event_scheduler = ON;4)     SET @@global.event_scheduler = ON;
Copy after login

键值1或者ON表示开启;0或者OFF表示关闭;

(三) 事件开启与关闭:

开启某事件:ALTER EVENT e_del_logs ON COMPLETION PRESERVE ENABLE;关闭某事件:ALTER EVENT e_del_logs ON COMPLETION PRESERVE DISABLE;
Copy after login

 

 

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template