mysql 定时任务job
1、通过show EVENTS显示当前定义的事件
2、检查event_scheduler状态:SHOW VARIABLES LIKE 'event_scheduler'
3、设置job自动启动可以执行:SET GLOBAL event_scheduler = 1;或修改my.ini文件,添加:event_scheduler=1
4、创建一张简单的测试表
CREATE TABLE `example` ( `id` varchar(50) DEFAULT NULL, `name` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8
5、创建一个简单的存储过程,执行数据插入任务
delimiter //
CREATE DEFINER=`root`@`localhost` PROCEDURE `pro_example`()
BEGIN
INSERT INTO example VALUES('example','example');
END
//
6、创建数据库定时任务
# 如果原来存在该名字的任务计划则先删除
drop event if exists example_event2;
CREATE DEFINER=`root`@`localhost` EVENT `example_event2`
ON SCHEDULE EVERY 1 MINUTE STARTS CURRENT_TIMESTAMP
ON COMPLETION NOT PRESERVE ENABLE
DO
call pro_example
;
2.
DROP EVENT IF EXISTS JOB_ALARM;
CREATE EVENT JOB_ALARM
ON SCHEDULE EVERY 10 MINUTE
DO
BEGIN
if(date_format(current_time(),'%H')>22 || date_format(current_time(),'%H')<5) THEN
CALL PRO_ALARM();
END IF;
END
查看example表可以发现,每隔一分钟会多出一条记录。
# 停止
ALTER EVENT example_event2 DISABLE;
# 开启
alter event example_event2 enable;
注意:真实的开发环境中,会遇到mysql服务重启或者断电的情况,此时则会出现事件调度器被关闭的情况,所有事件都不在起作用,要想解决这个办法,则需要在mysql.ini文件中加入event_scheduler = ON; 的语句
创建事件语法:
CREATE EVENT [IF NOT EXISTS] event_name ON SCHEDULE schedule [ON COMPLETION [NOT] PRESERVE] [ENABLE | DISABLE] [COMMENT 'comment'] DO sql_statement; schedule: AT TIMESTAMP [+ INTERVAL INTERVAL] | EVERY INTERVAL [STARTS TIMESTAMP] [ENDS TIMESTAMP] INTERVAL: quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE | WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE | DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}
修改事件语法:
ALTER EVENT event_name [ON SCHEDULE schedule] [RENAME TO new_event_name] [ON COMPLETION [NOT] PRESERVE] [COMMENT 'comment'] [ENABLE | DISABLE] [DO sql_statement]