在很多实际的项目中,定时执行某些逻辑很是多见;很多小伙伴立马会想到quartz定时框架,但是今天笔者要向大家介绍如何在mysql编写定时调度器。
①mysql中函数或存储过程的编写
DROP PROCEDURE IF EXISTS `hero`; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `hero`() BEGIN INSERT INTO `user`(uname,age) VALUES("helloword",520); END ;; DELIMITER ;
DEFINER: 定义事件执行的时候检查权限的用户;以上代码全在mysql中执行;当执行以上代码时,可能会报调度器关闭状态的错误,执行如下代码查看mysql调度器状态
show variables like '%sched%'; //查询Event Scheduler开启状态
笔者已经开启了,如果处于关闭状态,mysql中执行如下代码
开启 Event Scheduler,以下4种方式等效 SET GLOBAL event_scheduler = ON; SET @@global.event_scheduler = ON; SET GLOBAL event_scheduler = 1; SET @@global.event_scheduler = 1; 关闭 Event Scheduler,以下4种方式等效 SET GLOBAL event_scheduler = OFF; SET @@global.event_scheduler = OFF; SET GLOBAL event_scheduler = 0; SET @@global.event_scheduler = 0;
②创建调度事件
CREATE EVENT if not exists zhang on schedule every 3 second on completion preserve do call hero();
ON SCHEDULE schedule: 定义执行的时间和时间间隔;
ON COMPLETION [NOT] PRESERVE: 定义事件是一次执行还是永久执行,默认为一次执行,即NOT PRESERVE。
禁用调度事件 alter event zhang disable; 开启调度事件 alter event zhang enable;
定时器执行结果:
查询数据库调度事件列表 select * from mysql.event;
①定时在某时刻开始,每隔多长时长执行
CREATE EVENT insertUser ON SCHEDULE EVERY 1 SECOND STARTS CURRENT_TIMESTAMP + INTERVAL 1 MINUTE DO INSERT into user(uname,age) VALUES("test",250);
②定时在某时刻停止执行定时调度事件
CREATE EVENT goodHeart ON SCHEDULE EVERY 1 SECOND ENDS CURRENT_TIMESTAMP + INTERVAL 30 SECOND DO INSERT INTO user(uname,age) VALUES("helloworld",520);③定时清空某表的数据
CREATE EVENT halou ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 10 SECOND DO TRUNCATE TABLE `user`;
④传参的存储过程
create procedure test_produre ( a int, b int ) begin declare c int; if a is null then set a = 0; end if; if b is null then set b = 0; end if; set c = a + b; select c as sum; end;然后调用存储过程
好了,我是张星,欢迎大家加入博主技术交流群,群号:313145288