Mysql本地任务调度
MySQL5.1.x 版本中引入了一项新特性 EVENT ,顾名思义就是事件、定时任务机制,在指定的时间单元内执行特定的任务,因此今后一些对数据定时性操作不再依赖外部程序,而直接使用数据库本身提供的功能。此功能是对 Oracle 的 Job/Schedule 的模仿, 5.1.X 版本以上才支持。
创建 EVENT 语法如下:
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 sql_statement;
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}
例如创建一个每 30 秒清空 tableA 数据的任务
CREATE EVENT E_DELETE_ASO_TOKEN ON SCHEDULE EVERY 30 SECOND DO DELETE FROM tableA ;
默认 EVENT 支持是没有启动的,可以通过下面的命令来查看状态:
Select @@event_scheduler;
如果返回 OFF ,则需要执行下面的命令启动:
SET GLOBAL event_scheduler = ON;
好了,上面虽然启动了 EVENT ,但是每次重启 mysql 之后 EVENT 并没有自动启动,那么如何让它自动启动呢?
方法一:找到当前使用的 .cnf 文件,在 [mysqld] 的下面加入如下行
event_scheduler=1
方法二:启动 mysql 的时候增加 --event_scheduler=1
mysql start --event_scheduler=1
事件详细语法事例 (EVENT)
1> 创建事件 (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 秒钟后,再执行查询看看:
mysql> SELECT * FROM aaa;
+---------------------+
| timeline |
+---------------------+
| 2007-07-18 20:44:26 |
| 2007-07-18 20:44:27 |
| 2007-07-18 20:44:28 |
+---------------------+
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
&nb