日期:2014-05-16  浏览次数:20708 次

mysql中的event事件控制
mysql 中的event 在5.1及以上被支持,下面简单讲解下

1  启用
   mysql> SET GLOBAL event_scheduler = ON;
  关闭
    SET GLOBAL event_scheduler = OFF;

2 注意的是event一旦创建后,则只有创建者对它有权限操作,而且5.1的event规定了
event的名称为64个字母大小写倒不敏感,event中不能再创建修改和删除其他event.

3 创建一个event
   DELIMITER |

CREATE EVENT myevent
    ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
    DO
      BEGIN
        UPDATE mytable SET mycol = mycol + 1;
      END |

DELIMITER ;
    这里注意用|来表示结束符号。这个事件是每隔1个小时更新数据表一次了
可以通过SHOW EVENTS\G 去看事件,如下
mysql> SHOW EVENTS\G
********************** 1. row **********************
                  Db: mysql
                Name: myevent
             Definer: dbuser@localhost
           Time zone: SYSTEM
                Type: ONE TIME
          Execute At: 2011-10-26 20:24:19
      Interval Value: NULL
      Interval Field: NULL
              Starts: NULL
                Ends: NULL
              Status: ENABLED
          Originator: 0
character_set_client: utf8
collation_connection: utf8_general_ci

  event在完成后会自动结束,除非显式地声明关闭,即
CREATE EVENT myevent
    ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
    ON COMPLETION PRESERVE
    DO
      BEGIN
        UPDATE mytable SET mycol = mycol + 1;
      END |
使用on completion即可
event结束后,其实还留在数据库中,除非drop掉,即
DROP EVENT myevent;
如果要循环执行event,用every,即

  CREATE EVENT myevent
    ON SCHEDULE EVERY 1 HOUR
    DO
      BEGIN
        UPDATE mytable SET mycol = mycol + 1;
      END |

也可以指定开始和结束时间
CREATE EVENT myevent
    ON SCHEDULE EVERY 1 HOUR
    STARTS CURRENT_TIMESTAMP + INTERVAL 1 DAY
    ENDS CURRENT_TIMESTAMP + INTERVAL 1 YEAR
    DO
      BEGIN
        UPDATE mytable SET mycol = mycol + 1;
      END |

当然,INTERVAL后可以跟day,year,month,hour,minutes,seconds等了
也可以更新event,比如

ALTER EVENT myevent
    ON SCHEDULE EVERY 1 MONTH
    STARTS '2011-12-01 01:00:00' |
更名:
  ALTER EVENT myevent
    RENAME TO yourevent;

在PHP代码中,也可以执行event,比如:
  $query = "CREATE EVENT publish_:id 

    ON SCHEDULE AT FROM_UNIXTIME(:scheduleDate) 

  DO 

     BEGIN 

        UPDATE blog_posts SET status = 'published' WHERE id = :id; 

     END";&n