MySQL event的簡單使用

來源:互聯網
上載者:User

MySQL event的簡單使用

—— 查看event的create資訊

SHOW CREATE event event_test;


——查看某個schema下的event狀態

SELECT event_schema,event_name,STATUS FROM information_schema.events WHERE event_schema = 'xxxx'

 

——查看event功能是否開啟

mysql> show variables like '%event%';

+-----------------+-------+

| Variable_name  | Value |

+-----------------+-------+

| event_scheduler | OFF  |

+-----------------+-------+

1 row in set (0.00 sec)

 

開啟event功能,可設定為ON|1

mysql> set global event_scheduler=on;

Query OK, 0 rows affected (0.00 sec)

 

mysql> show variables like '%event%';

+-----------------+-------+

| Variable_name  | Value |

+-----------------+-------+

| event_scheduler | ON    |

+-----------------+-------+

1 row in set (0.00 sec)

 

-- 建立測試表

CREATE TABLE t(X DATETIME);


 -- 建立一個測試的proc,為了向測試表中插入系統時間

DELIMITER $$

DROP PROCEDURE IF EXISTS e_test $$

CREATE PROCEDURE e_test()

BEGIN

INSERT INTO t VALUES(NOW());

END $$

DELIMITER ;

 

-- 建立事件

--每隔十秒自動調用e_test()預存程序

CREATE EVENT IF NOT EXISTS event_test

ON SCHEDULE EVERY 10 SECOND

ON COMPLETION PRESERVE

DO CALL e_test();  

 

過會兒select測試表中的資料,如下:
 


-- 開啟事件

  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

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.