创建存储过程,这里的存储过程主要提供给mysql的定时器event来调用去执行:
delimiter //
drop procedure if exists mypro//
create procedure mypro()
begin
insert into test(time) values(now());
end//
delimiter ;
这里只是简单的写了一下,只是为了说明例子。
紧接着创建mysql的定时器event:
drop event if exists eventJob ;
create event if not exists eventJob
on schedule every 1 second
on completion PRESERVE
do call mypro();
这里设置为每一秒执行一次
至此所有的准备工作已经写完了,做完这些,mysql要想利用定时器必须的做准备工作,就是把mysql的定时器给开启了:
SET GLOBAL event_scheduler = 1; -- 启动定时器
SET GLOBAL event_scheduler = 0; -- 停止定时器
紧接着还要开启事件:
ALTER EVENT eventJob ON COMPLETION PRESERVE ENABLE; -- 开启事件
ALTER EVENT eventJob ON COMPLETION PRESERVE DISABLE; -- 关闭事件
SHOW VARIABLES LIKE '%sche%'; -- 查看定时器状态
每天凌晨三点执行
create event event_call_defer
on schedule every 1 day starts date_add(date(curdate() + 1),interval 3 hour)
on completion preserve enable
do
begin
call test.warn();
end
每个月的一号凌晨1 点执行
CREATE EVENT EVENT2
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 STAT();
END
每个季度一号的凌晨2点执行
CREATE EVENT TOTAL_SEASON_EVENT
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
BEGIN
CALL SEASON_STAT();
END
每年1月1号凌晨四点执行
CREATE EVENT TOTAL_YEAR_EVENT
ON SCHEDULE EVERY 1 YEAR STARTS DATE_ADD(DATE(CONCAT(YEAR(CURDATE()) + 1,'-',1,'-',1)),INTERVAL 4 HOUR)
ON COMPLETION PRESERVE ENABLE
DO
BEGIN
CALL YEAR_STAT();
END