mysql中的定時器及儲存過程
阿新 • • 發佈:2019-02-08
需求:今天遇到mysql中的日誌表需要設定最大儲存量、最多儲存天數,多餘的刪除
儲存過程程式碼如下:
DELIMITER // DROP PROCEDURE if exists log_system; CREATE PROCEDURE log_system (in u_n INT,u_d INT,s_n INT,s_d INT)//u_d使用者日誌天數,u_n使用者日誌數,s_n系統日誌數,s_d系統日誌天數 BEGIN SET u_d = (SELECT userloggingDate FROM logging_prameter); //通過設定表得到使用者日誌天數 DELETE FROM user_logging WHERE time <= (select date_add(sysdate(),interval - u_d day) as yestoday);//通過演算法算出系統時間前去使用者日誌天數,得到應該刪除的時間點 IF (SELECT COUNT(*) FROM user_logging) > (SELECT userLoggingNumber FROM logging_prameter) THEN SET u_n = (select COUNT(*) FROM user_logging)-(SELECT userLoggingNumber FROM logging_prameter); DELETE FROM user_logging ORDER BY time LIMIT u_n; END IF; SET s_d = (SELECT sysLoggingDate FROM logging_prameter); DELETE FROM sys_logging WHERE time <= (select date_add(sysdate(),interval - s_d day) as yestoday); IF (SELECT COUNT(*) FROM sys_logging) > (SELECT sysLoggingNumber FROM logging_prameter) THEN SET s_n = (select COUNT(*) FROM sys_logging)-(SELECT sysLoggingNumber FROM logging_prameter); DELETE FROM sys_logging ORDER BY time LIMIT s_n; END IF; END; //DELIMITER
定時器程式碼如下:
DELIMITER // SET GLOBAL event_scheduler = ON; DROP EVENT IF EXISTS `eventSysUserLogging`; CREATE EVENT IF NOT EXISTS `eventSysUserLogging` ON SCHEDULE EVERY 1 DAY STARTS TIMESTAMP(CURRENT_DATE,'17:30:00') ON COMPLETION PRESERVE ENABLE DO BEGIN CALL log_system(@u_n,@u_n,@s_n,@s_d);//呼叫儲存過程 END; // DELIMITER