1. 程式人生 > >mysql事件【定時器】

mysql事件【定時器】

一,借鑑【luo奔的蝸牛

1.建立一張表

1 create table mytable (
2 id int auto_increment not null,
3 name varchar(100) not null default '',
4 introduce text not null,
5 createtime timestamp not null,
6 constraint pk_mytable primary key(id)
7 )
View Code

2.建立儲存過程

1 --建立儲存過程,這裡的儲存過程主要提供給mysql的定時器event來呼叫去執行:
2 create procedure proc() 3 begin 4 insert into mytable (name,introduce,createtime) values ('週三','000',now()); 5 end;
View Code

 

緊接著建立mysql的定時器event:
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%'; -- 檢視定時器狀態


至此,你去資料庫裡面的表mytable裡面看下,系統會每隔一秒去插入一條資料,嘻嘻,任務完成了。
select * from mytable