要查看當前是否已開啟事件調度器,可執行如下SQL:
SHOW VARIABLES LIKE 'event_scheduler';
或
SELECT @@event_scheduler;
或
SHOW PROCESSLIST;
若顯示:
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| event_scheduler | OFF |
+-----------------+-------+
則可執行
SET GLOBAL event_scheduler = 1;
或
SET GLOBAL event_scheduler = ON;
來開啟,也可以直接在啟動命令加上“–event_scheduler=1”,例如:
mysqld ... --event_scheduler=1
my.ini or my.cnf 中的
[mysqld]
添加 event_scheduler=ON
創建事件(CREATE EVENT)
先來看一下它的語法:
CREATE EVENT [IF NOT EXISTS] event_name
ON SCHEDULE schedule
[ON COMPLETION [NOT] PRESERVE]
[ENABLE | DISABLE]
[COMMENT 'comment']
DO sql_statement;
schedule:
AT TIMESTAMP [+ INTERVAL INTERVAL]
| EVERY INTERVAL [STARTS TIMESTAMP] [ENDS TIMESTAMP]
INTERVAL:
quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |
WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |
DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}
1)首先來看一個簡單的例子來演示每秒插入一條記錄到數據表
USE test;
CREATE TABLE aaa (timeline TIMESTAMP);
CREATE EVENT e_test_insert
ON SCHEDULE EVERY 1 SECOND
DO INSERT INTO test.aaa VALUES (CURRENT_TIMESTAMP);
等待3秒鐘後,再執行查詢成功。
2) 5天後清空test表:
CREATE EVENT e_test
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 DAY
DO TRUNCATE TABLE test.aaa;
3) 2007年7月20日12點整清空test表:
CREATE EVENT e_test
ON SCHEDULE AT TIMESTAMP '2007-07-20 12:00:00'
DO TRUNCATE TABLE test.aaa;
4) 每天定時清空test表:
CREATE EVENT e_test
ON SCHEDULE EVERY 1 DAY
DO TRUNCATE TABLE test.aaa;
5) 5天後開啟每天定時清空test表:
CREATE EVENT e_test
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_TIMESTAMP + INTERVAL 5 DAY
DO TRUNCATE TABLE test.aaa;
6) 每天定時清空test表,5天後停止執行:
CREATE EVENT e_test
ON SCHEDULE EVERY 1 DAY
ENDS CURRENT_TIMESTAMP + INTERVAL 5 DAY
DO TRUNCATE TABLE test.aaa;
7) 5天後開啟每天定時清空test表,一個月後停止執行:
CREATE EVENT e_test
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_TIMESTAMP + INTERVAL 5 DAY
ENDS CURRENT_TIMESTAMP + INTERVAL 1 MONTH
DO TRUNCATE TABLE test.aaa;
[ON COMPLETION [NOT] PRESERVE]可以設置這個事件是執行一次還是持久執行,默認為NOT PRESERVE。
8) 每天定時清空test表(只執行一次,任務完成後就終止該事件):
CREATE EVENT e_test
ON SCHEDULE EVERY 1 DAY
ON COMPLETION NOT PRESERVE
DO TRUNCATE TABLE test.aaa;
[ENABLE | DISABLE]可是設置該事件創建後狀態是否開啟或關閉,默認為ENABLE。
[COMMENT ‘comment']可以給該事件加上注釋。
修改事件(ALTER EVENT)
ALTER EVENT event_name
[ON SCHEDULE schedule]
[RENAME TO new_event_name]
[ON COMPLETION [NOT] PRESERVE]
[COMMENT 'comment']
[ENABLE | DISABLE]
[DO sql_statement]
1) 臨時關閉事件
ALTER EVENT e_test DISABLE;
2) 開啟事件
ALTER EVENT e_test ENABLE;
3) 將每天清空test表改為5天清空一次:
ALTER EVENT e_test
ON SCHEDULE EVERY 5 DAY;
刪除事件(DROP EVENT)
語法很簡單,如下所示:
DROP EVENT [IF EXISTS] event_name
例如刪除前面創建的e_test事件
DROP EVENT e_test;
當然前提是這個事件存在,否則會產生ERROR 1513 (HY000): Unknown event錯誤,因此最好加上IF EXISTS
DROP EVENT IF EXISTS e_test;