事件 计划任务(定期定时执行)

-- 查看当前mysql数据库是否开启时间功能,默认关闭
SHOW VARIABLES LIKE 'event_scheduler';

-- event_scheduler OFF
SET GLOBAL event_scheduler=1;-- ON 开启时间功能
SET GLOBAL event_scheduler=0;-- off 关闭
SET GLOBAL event_scheduler=ON;
SET GLOBAL event_scheduler=OFF;

CREATE TABLE eee
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
t2 TINYINT,
PRIMARY KEY(id)
)
SELECT * FROM eee;
DROP TABLE eee;
-- 定义一个事件 开始执行
CREATE EVENT myevent1
ON SCHEDULE EVERY 1 SECOND
DO INSERT INTO eee(t2) VALUES(10);

DELIMITER//
CREATE EVENT `myevent1`
ON SCHEDULE EVERY 2 SECOND
DO
BEGIN
INSERT INTO eee(t2) VALUES(10);
INSERT INTO eee(t2) VALUES(20);
INSERT INTO eee(t2) VALUES(30);
INSERT INTO eee(t2) VALUES(40);
END//
DELIMITER;
-- 禁用启用某个事件
ALTER EVENT myevent1 DISABLE;

ALTER EVENT myevent1 ENABLE;

-- 五天后清空Test表
CREATE EVENT e_test
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 DAY
DO TRUNCATE TABLE test;

-- 2007年7月20日12点整清空表test
CREATE EVENT e_test
ON SCHEDULE AT TIMESTAMP '2007-7-20 12:00:00';
DO TRUNCATE TABLE test;

-- 每天定时清空test表
CREATE EVENT e_test
ON SCHEDULE EVERY 1 DAY
DO TRUNCATE TABLE test;

-- 五天后开启每天定时清理
CREATE EVENT e_test
ON SCHEDULE EVERY 1 DAY
START CURRENT_TIMESTAMP + INTERVAL 5 DAY
DO TRUNCATE TABLE test;

-- 5天后开启每天定时清空test表,一个月后停止执行
CREATE EVENT e_test
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_TIMESTAMP + INTERVAL 5 DAY
ENDS CURRENT_TIMESTAMP + INTERVAL 1 MONTH
DO TRUNCATE TABLE test;

[ON COMPLETION[NOT] PRESERVE ]可以设置这个事件是执行一次还是持久执行 默认为 NOT PRESERVE
-- 每天定时清理test表(执行一次,任务完成后就终止该事件)
CREATE EVENT e_test
ON SCHEDULE EVERY 1 DAY
ON COMPLETION NOT PRESERVE
DO TRUNCATE TABLE test;

-- 将每天清空改为五天清空一次
ALTER EVENT e_test
ON SCHEDULE EVERY 5 DAY;

-- 删除事件(drop event)
DROP EVENT IF EXISTS myevent1;

-- 每分钟插入一条记录
DELIMITER//
CREATE EVENT `user_log_event`
ON SCHEDULE EVERY 1 MINUTE
STARTS '2010-12-6 00:00:00'
ON COMPLETION NOT PRESERVE ENABLE
DO
BEGIN INSERT INTO LOG SET ADDTIME=NEW();
END//
DELIMITER;

-- 调用存储过程
DELIMITER//
CREATE EVENT `user_log_event`
ON SCHEDULE EVERY 1 MINUTE
STARTS '2010-12-6 00:00:00'
ON COMPLETION NOT PRESERVE ENABLE
DO
BEGIN
CALL user_log_prov();
END//
DELIMITER;

05-02 00:37