欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL计划任务(事件调度器) Event Scheduler介绍

程序员文章站 2024-02-24 21:51:16
要查看当前是否已开启事件调度器,可执行如下sql: show variables like 'event_scheduler';或 select @@event_sch...

要查看当前是否已开启事件调度器,可执行如下sql:

show variables like 'event_scheduler';

select @@event_scheduler;

show processlist;
若显示:

+-----------------+-------+
| variable_name   | value |
+-----------------+-------+
| event_scheduler | off   |
+-----------------+-------+
则可执行

set global event_scheduler = 1;

set global event_scheduler = on;
来开启,也可以直接在启动命令加上“–event_scheduler=1”,例如:

mysqld ... --event_scheduler=1

my.ini or my.cnf 中的
[mysqld]
添加 event_scheduler=on

创建事件(create event)
先来看一下它的语法:

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}

1)首先来看一个简单的例子来演示每秒插入一条记录到数据表

use test;
create table aaa (timeline timestamp);
create event e_test_insert
on schedule every 1 second
do insert into test.aaa values (current_timestamp);
等待3秒钟后,再执行查询成功。

2) 5天后清空test表:

create event e_test
on schedule at current_timestamp + interval 5 day
do truncate table test.aaa;

3) 2007年7月20日12点整清空test表:

create event e_test
on schedule at timestamp '2007-07-20 12:00:00'
do truncate table test.aaa;

4) 每天定时清空test表:

create event e_test
on schedule every 1 day
do truncate table test.aaa;

5) 5天后开启每天定时清空test表:

create event e_test
on schedule every 1 day
starts current_timestamp + interval 5 day
do truncate table test.aaa;

6) 每天定时清空test表,5天后停止执行:

create event e_test
on schedule every 1 day
ends current_timestamp + interval 5 day
do truncate table test.aaa;

7) 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.aaa;
[on completion [not] preserve]可以设置这个事件是执行一次还是持久执行,默认为not preserve。

8) 每天定时清空test表(只执行一次,任务完成后就终止该事件):

create event e_test
on schedule every 1 day
on completion not preserve
do truncate table test.aaa;
[enable | disable]可是设置该事件创建后状态是否开启或关闭,默认为enable。
[comment ‘comment']可以给该事件加上注释。

修改事件(alter event)
alter event event_name
[on schedule schedule]
[rename to new_event_name]
[on completion [not] preserve]
[comment 'comment']
[enable | disable]
[do sql_statement]
1) 临时关闭事件

alter event e_test disable;

2) 开启事件

alter event e_test enable;
3) 将每天清空test表改为5天清空一次:

alter event e_test
on schedule every 5 day;

删除事件(drop event)
语法很简单,如下所示:

drop event [if exists] event_name
例如删除前面创建的e_test事件

drop event e_test;
当然前提是这个事件存在,否则会产生error 1513 (hy000): unknown event错误,因此最好加上if exists

drop event if exists e_test;