时间:2021-07-01 10:21:17 帮助过:13人阅读
MySQL定时任务event
由于一些业务需求,我们可能需要定时清除数据库一些废弃的数据,可以使用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;
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这个存储过程,并带上参数
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(SENDTIME)))>=date_inter;END$$DELIMITER ;
按事件传过来的参数90,删除操作时间90天之前的数据这样mysql就会定制每天去执行这个任务了。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;
开启某事件:ALTER EVENT e_del_logs ON COMPLETION PRESERVE ENABLE;关闭某事件:ALTER EVENT e_del_logs ON COMPLETION PRESERVE DISABLE;