使用MySQL的EVENT的语句,可以帮助我们完成一些定时任务
CREATE
[DEFINER = user]
EVENT
[IF NOT EXISTS]
event_name
ON SCHEDULE schedule
[ON COMPLETION [NOT] PRESERVE]
[ENABLE | DISABLE | DISABLE ON SLAVE]
[COMMENT 'string']
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}
**此语句会创建并计划一个新事件。在我们启用了事件计划程序,该事件才会自动运行,否则事件不会运行。**通常一旦某个事件过期,就会被立即删除
事件名不区分大小写,长度为64个字符,事件名必须唯一。
# 该语句会创建一个事件,该事件会从当前时间开始,20天之后结束,没隔5天执行一次并更新数据库的数据
create event if not exists myevent
on schedule every 5 day
starts current_date
ends date_add(current_date, interval 20 day)
do update data_test set day = day + 1;
# 该语句会创建一个事件,该事件会在一个小时候开始执行一次,并更新数据库的数据
create event if not exists myevent
on schedule at current_timestamp + interval 1 hour
do
update data_test
set day = day + 1;
alter
[definer = user]
event event_name
[on schedule schedule]
[on completion [not] preserve]
[rename to new_event_name]
[enable | disable | disable on slave]
[comment 'string']
[do event_body]
ALTER EVENT myevent DISABLE;
alter event myevent
on schedule
at current_timestamp + interval 1 day
do
truncate table data_test;
最后,欢迎关注微信公众号一起交流