標籤:
MySQL定時任務event,儲存過程(定時刪除指定時間前90天指定表的資料)分類: MySql5.x2014-06-23 15:16 1266人閱讀 評論(0) 收藏 舉報mysql資料庫
[sql] view plaincopy
- <span style="font-family: ‘Microsoft YaHei‘; font-size: 14px;">MySQL定時任務event</span>
由於一些業務需求,我們可能需要定時清除資料庫一些廢棄的資料,可以使用mysql的預存程序和事件來完成。下面例子定時清除日誌表tbl_base_count中指定天數前的資料1.建立日誌表tbl_base_count:
[sql] view plaincopy
- 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:
[sql] view plaincopy
- 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.建立預存程序:
[sql] view plaincopy
- 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種方法:
[sql] view plaincopy
- SHOW VARIABLES LIKE ‘event_scheduler‘;
- SELECT @@event_scheduler;
- SHOW PROCESSLIST;
5.(二)開啟事件計劃(調度器)開關有4種方法:
[sql] view plaincopy
- 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.(三)事件開啟與關閉:
[sql] view plaincopy
- 開啟某事件:ALTER EVENT e_del_logs ON COMPLETION PRESERVE ENABLE;
- 關閉某事件:ALTER EVENT e_del_logs ON COMPLETION PRESERVE DISABLE;
MySQL定時任務event,儲存過程(定時刪除指定時間前90天指定表的資料)