MySQL定时任务event,储存过程(定时删除指定时间前90天指定表的数据)
- <span style="font-family: 'Microsoft YaHei'; font-size: 14px;">MySQL定时任务event</span>
下面例子定时清除日志表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这个存储过程,并带上参数
- 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 ;
这样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;