MySQL从5.1开始支持Event功能,有点类似于MsSQL的Job,可以定时自动执行数据汇总。
【语法】
- 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}
其中,
event_name:定时器名,最大长度64个字符,若未指定,则默认为当前的MySQL用户名(不区分大小写);
schedule:限定执行时间;
ON COMPLETION [NOT] PRESERVE:表示是否需要循环复用这个Event;
sql_statement:要执行的SQL语句(也可以使用存储过程代替传统的SQL语句);
comment:对该时间调度器的一个注释,最大长度64个字符;
【关闭事件】
- ALTER EVENT event_name ON
- COMPLETION PRESERVE DISABLE;
- ALTER EVENT event_name ON
- COMPLETION PRESERVE ENABLE;
【删除事件】
- DROP EVENT [IF EXISTS] event_name
【注意】:要使用定时器,MySQL的常量GLOBAL event_scheduler必须为on或者是1.
【范例】
1. 每天凌晨1点开始执行数据更新:
- CREATE EVENT [IF NOT EXISTS] E_testEvent_1
- ON SCHEDULE EVERY 1 DAY STARTS DATE_ADD(DATE_ADD(CURDATE(), INTERVAL 1 DAY), INTERVAL 1 HOUR)
- ON COMPLETION PRESERVE ENABLE
- DO
- UPDATE _T_test SET col= 2 where ValidityDate < now();
2. 每月第一天凌晨1点开始执行数据更新(使用存储过程):
- CREATE EVENT E_testEvent_2
- 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 P_testProcedureName();
- END
3. 每季度第一天凌晨1点开始执行数据更新:
- CREATE EVENT E_testEvent_3
- 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
- UPDATE _T_test SET col= 2 where ValidityDate < now();
【一些Event相关语句】:
1. 查看是否开启定时器
- SHOW VARIABLES LIKE '%sche%';
2. 开启定时器 0:off 1:on
- SET GLOBAL event_scheduler = 1;
http://blog.csdn.net/abandonship/article/details/7050285
本文转自 liang3391 51CTO博客,原文链接:http://blog.51cto.com/liang3391/843182