--- 开启某个定时事件 alter event user_event on completion preserve enable;
关闭定时事件
1 2
--- 关闭某个定时事件 alter event user_event on completion preserve disable;
删除定时事件
1 2
--- 删除某个定时事件 drop event user_event;
常用定时事件案例
一次性执行
满足指定条件时,只会执行一次定时事件,然后定时事件结束执行
在未来指定时间点执行一次
1 2 3 4 5
DROP EVENT IF EXISTS user_event; CREATE EVENT user_event ON SCHEDULE ATTIMESTAMP'2023-09-24 18:26:00' ON COMPLETION NOT PRESERVE DO call user_procedure();
从现在开始 1 小时后执行一次
1 2 3 4 5
DROP EVENT IF EXISTS user_event; CREATE EVENT user_event ON SCHEDULE ATCURRENT_TIMESTAMP+INTERVAL1HOUR ON COMPLETION NOT PRESERVE DO call user_procedure();
周期性一直执行
定时事件一直周期性地执行
从现在开始每隔 N 天执行一次
1 2 3 4
DROP EVENT IF EXISTS user_event; CREATE EVENT user_event ON SCHEDULE EVERY9DAY STARTS NOW() DO call user_procedure();
每天凌晨 1 点执行
1 2 3 4
DROP EVENT IF EXISTS user_event; CREATE EVENT user_event on schedule EVERY1DAY STARTS date_add(date( ADDDATE(curdate(),1)),interval1hour) DO call user_procedure();
每个月的一号凌晨 1 点执行
1 2 3 4
DROP EVENT IF EXISTS user_event; CREATE EVENT user_event ON schedule every1month starts date_add(date_add(date_sub(curdate(),intervalday(curdate())-1day),interval1month),interval1hour) DO call user_procedure();
每个季度一号的凌晨 1 点执行
1 2 3 4
DROP EVENT IF EXISTS user_event; CREATE EVENT user_event ON schedule every1 quarter starts date_add(date_add(date(concat(year(curdate()),'-',elt(quarter(curdate()),1,4,7,10),'-',1)),interval1 quarter),interval1hour) DO call user_procedure();
每年 1 月 1 号凌晨 1 点执行
1 2 3 4
DROP EVENT IF EXISTS user_event; CREATE EVENT user_event ON schedule every1 quarter starts date_add(date_add(date(concat(year(curdate()),'-',elt(quarter(curdate()),1,4,7,10),'-',1)),interval1 quarter),interval1hour) DO call user_procedure();
周期性多次执行
定时事件执行多次后,在满足某个条件时,定时事件结束执行
从现在开始每天执行一次,5 天后停止执行
1 2 3 4 5
DROP EVENT IF EXISTS user_event; CREATE EVENT user_event ON SCHEDULE EVERY1DAY ENDS CURRENT_TIMESTAMP+INTERVAL5DAY DO call user_procedure();
从现在开始 5 天后开始执行,一个月后停止执行
1 2 3 4 5 6
DROP EVENT IF EXISTS user_event; CREATE EVENT user_event ON SCHEDULE EVERY1DAY STARTS CURRENT_TIMESTAMP+INTERVAL5DAY ENDS CURRENT_TIMESTAMP+INTERVAL1MONTH DO call user_procedure();