【MySQL】MySQL定時器

建立測試表
CREATE TABLE t
(
    v VARCHAR(100) NOT NULL
) ENGINE INNODB DEFAULT CHARSET=utf8;
建立定時器 調用的存儲過程
DELIMITER $$
DROP PROCEDURE IF EXISTS e_test $$
CREATE PROCEDURE e_test() 
    BEGIN
        INSERT INTO t VALUES('1');
    END $$
DELIMITER ;
 要使定時起做用 MySQL的常量GLOBAL event_scheduler必須爲on或者是1 

-- 查看是否開啓定時器
SHOW VARIABLES LIKE '%sche%';

-- 開啓定時器 0:off 1:on
SET GLOBAL event_scheduler = 1;

-- 建立事件


--每隔一秒自動調用e_test()存儲過程
CREATE EVENT IF NOT EXISTS event_test
ON SCHEDULE EVERY 1 SECOND
ON COMPLETION PRESERVE   
DO CALL e_test();
-- 開啓事件

ALTER EVENT event_test ON    
COMPLETION PRESERVE ENABLE;
 
-- 關閉事件

ALTER EVENT event_test ON    
COMPLETION PRESERVE DISABLE;


從如今開始每隔九天定時執行  
CREATE  EVENT EVENT1  
ON SCHEDULE EVERY 9 DAY STARTS NOW()  
ON COMPLETION PRESERVE ENABLE  
DO 
    BEGIN  
       CALL TOTAL();  
    END

每月的一號凌晨1 點執行  

CREATE  EVENT EVENT2     
ON SCHEDULE EVERY 1 MONTH STARTS DATE_ADD(DATE_ADD(DATE_SUB(CURDATE(),INTERVAL DAY(CURDATE())-1 DAY), INTERVAL 1 MONTH),INTERVAL 1 HOUR)  
ON COMPLETION PRESERVE ENABLE  
DO  
    BEGIN  
        CALL STAT();  
    END


每一個季度一號的凌晨2點執行  

CREATE  EVENT TOTAL_SEASON_EVENT  
ON SCHEDULE EVERY 1 QUARTER STARTS DATE_ADD(DATE_ADD(DATE( CONCAT(YEAR(CURDATE()),'-',ELT(QUARTER(CURDATE()),1,4,7,10),'-',1)),INTERVAL 1 QUARTER),INTERVAL 2 HOUR)  
ON COMPLETION PRESERVE ENABLE  
DO  
    BEGIN  
        CALL SEASON_STAT();  
    END

每一年1月1號凌晨四點執行  
CREATE  EVENT TOTAL_YEAR_EVENT  
ON SCHEDULE EVERY 1 YEAR STARTS DATE_ADD(DATE(CONCAT(YEAR(CURDATE()) + 1,'-',1,'-',1)),INTERVAL 4 HOUR)  
ON COMPLETION PRESERVE ENABLE  
DO  
    BEGIN  
        CALL YEAR_STAT();  
    END
   MySQL的event在進行按月,季,年進行自動調用存儲過程時,爲了測試能夠把系統改成年的最後一天,如2010-12-31 23:59:55;
相關文章
相關標籤/搜索