MySQL提供了定时机制以定时操作数据库脚本。

首先需要查看事件调度是否开启

SHOW VARIABLES LIKE 'event%';数据库会做出如下反应

+-----------------+-------+| Variable_name   | Value |+-----------------+-------+| event_scheduler | OFF   |+-----------------+-------+1 row in set (0.00 sec)如果此处显示的是OFF,那么需要开启事件调度:

SET GLOBAL EVENT_SCHEDULER = 1;操作事件查看事件

SHOW EVENTS;创建事件

这是创建事件的完整代码,具体可以见示例

CREATE [DEFINER = { user | CURRENT_USER}] EVENT    [IF NOT EXISTS] event_name    ON SCHEDULE schedule    [ON COMPLETION [NOT] PRESERVE]    [ENABLE | DISABLE | DISABLE ON SLAVE]    [COMMENT 'comment']    DO event_body;schedule:    AT timestamp [+ INTERVAL interval]... | EVERY interval    [STARTS timestamp [+ INTERVAL interval] ...]    [ENDS timestamp [+ INTERVAL interval] ...]interval:    quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE | WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE | DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}删除事件

DROP EVENT event_name;开启和关闭事件

ALTER EVENT e_test DISABLE; ALTER EVENT e_test ENABLE;更新事件

更新事件中的每一项都是可选的,因此可以在这里更新事件的所有属性

ALTER    [DEFINER = { user | CURRENT_USER }]    EVENT event_name    [ON SCHEDULE schedule]    [ON COMPLETION [NOT] PRESERVE]    [RENAME TO new_event_name]    [ENABLE | DISABLE | DISABLE ON SLAVE]    [COMMENT 'comment']    [DO event_body] 示例1. 每秒钟执行一次

CREATE EVENT e_test_insert ON SCHEDULE EVERY 1 SECOND DO INSERT INTO test VALUES (1);2. 当前时间5天后清空result表

CREATE EVENT e_test ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 DAYDO TRUNCATE TABLE result;3. 在特定时间清空result表

CREATE EVENT e_test ON SCHEDULE AT TIMESTAMP '2015-05-12 12:00:00'DO TRUNCATE TABLE result4. 每天相同时间清空result表

CREATE EVENT e_test ON SCHEDULE EVERY 1 DAYDO TRUNCATE TABLE result;5. 每天定时清空result表,5天后开始

CREATE EVENT e_test ON SCHEDULE EVERY 1 DAYSTARTS CURRENT_TIMESTAMP + INTERVAL 5 DAYDO TRUNCATE TABLE result;6. 每天定时清空result表,5天后停止

CREATE EVENT e_test ON SCHEDULE EVERY 1 DAYENDS CURRENT_TIMESTAMP + INTERVAL 5 DAYDO TRUNCATE TABLE result7. 每天定时清空test表,5天后开启,一个月后停止

CREATE EVENT e_test ON SCHEDULE EVERY 1 DAYSTARTS CURRENT_TIMESTAMP + INTERVAL 5 DAYENDS CURRENT_TIMESTAMP + INTERVAL 1 MONTHDO TRUNCATE TABLE result;8. 每天定时清空test表(只执行一次,任务完成后就终止)