<span style="font-family: 'Microsoft YaHei'; font-size: 14px;">MySQL定时任务event</span>
로그인 후 복사
由于一些业务需求,我们可能需要定时清除数据库一些废弃的数据,可以使用mysql的存储过程和事件来完成。下面例子定时清除日志表tbl_base_count中指定天数前的数据1.创建日志表tbl_base_count:
CREATE TABLE `tbl_base_count` ( `id` int(11) NOT NULL AUTO_INCREMENT, `CAPTCHA` varchar(12) COLLATE utf8_bin NOT NULL, `PHONE` varchar(12) COLLATE utf8_bin NOT NULL, `SENDTIME` varchar(32) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
로그인 후 복사
2.创建事件e_del_tbl_base_count:
CREATE EVENT `e_del_tbl_base_count` ON SCHEDULE EVERY 1 DAY STARTS '2013-06-23 17:33:43' ON COMPLETION NOT PRESERVE ENABLE DO CALL p_del_count (90);
로그인 후 복사
上面代码表示从2013-07-30 17:33:43起每一天执行一次p_del_count这个存储过程,并带上参数
3.创建存储过程:
p_del_count DELIMITER $$---- 存储过程--CREATE PROCEDURE `p_del_count`(IN `date_inter` INT)BEGIN DELETE FROM LOG WHERE (TO_DAYS(NOW()) - TO_DAYS(FROM_UNIXTIME(<span style="font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;">SENDTIME</span>)))>=date_inter;END$$DELIMITER ;
로그인 후 복사
按事件传过来的参数90,删除操作时间90天之前的数据这样mysql就会定制每天去执行这个任务了。
4.(一)查看当前是否已开启事件计划(调度器)有3种方法:
SHOW VARIABLES LIKE 'event_scheduler'; SELECT @@event_scheduler; SHOW PROCESSLIST;
로그인 후 복사
5.(二)开启事件计划(调度器)开关有4种方法:
SET GLOBAL event_scheduler = 1; SET @@global.event_scheduler = 1; SET GLOBAL event_scheduler = ON; SET @@global.event_scheduler = ON;
로그인 후 복사
键值1或者ON表示开启;0或者OFF表示关闭;
6.(三)事件开启与关闭:
开启某事件:ALTER EVENT e_del_logs ON COMPLETION PRESERVE ENABLE;关闭某事件:ALTER EVENT e_del_logs ON COMPLETION PRESERVE DISABLE;
로그인 후 복사