mysql 定时任务执行

niewj
SET GLOBAL event_scheduler = ON;  

show variables like 'event_scheduler';  
 event_scheduler ON

创建event:

CREATE EVENT my_event   
  
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 10 SECOND   
  
DO  
    UPDATE tbl1 SET pic_count = pic_count + 10 WHERE uname = 'aaaa';  

查看待执行event:

show events  

为空说明已经执行完了。

以上分为三部分:

1. create event
  创建执行活动
2. on schedule
  执行周期以及起始时间等
#schedule:  
    AT timestamp [+ INTERVAL interval] ... | EVERY interval    [STARTS timestamp [+ INTERVAL interval] ...][ENDS timestamp [+ INTERVAL interval] ...]  
两种:1.在某个时间点执行:at 某个时间点+某个时间长度:
        如上面的:AT CURRENT_TIMESTAMP + INTERVAL 10 SECOND 标识从现在起,10秒后执行;

      2.周期性执行:every 每间隔多长时间执行一次,从 某时间点开始,到某个时间点结束。

        从现在起每隔5秒修改数据,50秒后停止。
CREATE EVENT my_event2   
ON SCHEDULE EVERY 5 SECOND  
      ENDS CURRENT_TIMESTAMP + INTERVAL 50 SECOND  
DO  
    UPDATE t1   SET pic_count = pic_count + 2 WHERE uname = 'aaaa';  

周期的具体单位值:

interval:
    quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |
              WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |
              DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}

<3>do

具体要执行的动作sql.

举例:定时清理表c_amount 3天前的数据,5个小时10分钟后启动(第一次执行)。

CREATE EVENT e_c_amount_delete_3_days_ago  
ON SCHEDULE EVERY 1 DAY  
        STARTS CURRENT_TIMESTAMP + INTERVAL '05:10' HOUR_MINUTE  
DO delete from c_amount where modify_time < DATE_SUB(CURDATE(),INTERVAL 3 DAY) 

[2015-06-01]

阅读 504

遇见超乎想象的自己!

245 声望
5 粉丝
0 条评论

遇见超乎想象的自己!

245 声望
5 粉丝
宣传栏