mysql数据库上使用定时器定时执行存储过程建表(月表)

时间:2023-01-31 23:30:37

最近有个需求,在mysql数据库中每个月建自动一个表,把该月的数据存储到该月对应的表中。

一、创建存储过程

期望表名:
login_history_2017_07(login_history_YYYY_MM)
字段:
id (int(11) primary key auto_increment)
uid (char(10) not null)
ip (char(200) not null)

DELIMITER //
create procedure create_login_history_table()
begin
set @tbCreate = concat('create table ','login_history_',date_format(now(),'%YYYY_%mm'),"(
id int(11)
primary key auto_increment,
uid char(10) not null,
ip char(200) not null)ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='登录信息记录'");

prepare stmt from @tbCreate;
execute stmt;
end;//

create_login_history_table():存储过程名称
set @tbCreate:定义变量@tbCreate
concat():拼接所有参数返回字符串
date_format():第一个参数now()为当前时间的时间戳,第二个参数’%YYYY_%mm’把时间格式化为例:2017_07格式字符串返回。

二、定义定时器

指定时间开始每个月执行一次存储过程create_login_history_table()

CREATE EVENT create_login_history_table ON SCHEDULE every 1 month STARTS TIMESTAMP '2017-08-01 00:00:00' do call create_login_history_table()

every 1 month:每个月执行一次
STARTS TIMESTAMP ‘2017-08-01 00:00:00’:在2017-08-01 00:00:00开始执行

PS:

1、删除定时器
drop event create_login_history_table;
2、暂停定时器
ALTER EVENT create_login_history_table DISABLE;
3、启动定时器
ALTER EVENT create_login_history_table ENABLE;
4、修改定时器
ALTER EVENT create_login_history_table
   ON SCHEDULE EVERY 5 DAY;
5、一些定时例子
/*每10秒*/
create event create_login_history_table on schedule every 10 second do ...
/*2天后*/
CREATE EVENT create_login_history_table ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 2 DAY do ...
/*指定时间*/
CREATE EVENT create_login_history_table ON SCHEDULE AT TIMESTAMP '2017-08-01 00:00:00' do ...
/*每天*/
CREATE EVENT create_login_history_table ONSCHEDULE EVERY 1 DAY DO ...
/*每天定时执行,5天后停止执行*/
CREATE EVENT create_login_history_table ON SCHEDULE EVERY 1 DAY ENDS CURRENT_TIMESTAMP + INTERVAL 5 DAY
DO ...
/*5天后开启每天执行,一个月后停止执行*/
CREATE EVENT e_test ON SCHEDULE EVERY 1 DAY STARTS CURRENT_TIMESTAMP+ INTERVAL 5 DAY ENDS CURRENT_TIMESTAMP+ INTERVAL 1 MONTH DO ...