[转]mysql创建定时任务
一、前言 自 MySQL5.1.6起,增加了一个非常有特色的功能–事件调度器(Event Scheduler),可以用做定时执行某些特定任务(例如:删除记录、对数据进行汇总等等),来取代原先只能由操作系统的计划任务来执行的工作。更值得 一提的是MySQL的事件调度器可以精确
一、前言
自 MySQL5.1.6起,增加了一个非常有特色的功能–事件调度器(Event Scheduler),可以用做定时执行某些特定任务(例如:删除记录、对数据进行汇总等等),来取代原先只能由操作系统的计划任务来执行的工作。更值得 一提的是MySQL的事件调度器可以精确到每秒钟执行一个任务,而操作系统的计划任务(如:Linux下的CRON或Windows下的任务计划)只能精 确到每分钟执行一次。对于一些对数据实时性要求比较高的应用(例如:股票、赔率、比分等)就非常适合。
事件调度器有时也可称为临时触发器(temporal triggers),因为事件调度器是基于特定时间周期触发来执行某些任务,而触发器(Triggers)是基于某个表所产生的事件触发的,区别也就在这里。
在使用这个功能之前必须确保event_scheduler已开启,可执行
SET GLOBAL event_scheduler = 1;
---或我们可以在配置my.cnf文件 中加上 event_scheduler = 1
或
SET GLOBAL event_scheduler = ON;
来开启,也可以直接在启动命令加上“--event_scheduler=1”,例如:
mysqld ... --event_scheduler=1
要查看当前是否已开启事件调度器,可执行如下SQL:
SHOW VARIABLES LIKE 'event_scheduler';
或
SELECT @@event_scheduler;
或
SHOW PROCESSLIST;
二、创建事件(CREATE EVENT)
先来看一下它的语法:
1
|
CREATE ? EVENT [IF NOT ? EXISTS] event_name
|
2
|
? ON SCHEDULE schedule
|
3
|
[ ON COMPLETION [ NOT ] PRESERVE]
|
4
|
[ENABLE | DISABLE]
|
5
|
[COMMENT? 'comment' ]
|
6
|
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) 首先来看一个简单的例子来演示每秒插入一条记录到数据表
1
|
USE test;
|
2
|
CREATE TABLE ? aaa (timeline? TIMESTAMP );
|
3
|
CREATE EVENT e_test_insert
|
4
|
? ON SCHEDULE EVERY 1? SECOND
|
5
|
DO? INSERT INTO ? test.aaa? VALUES ( CURRENT_TIMESTAMP );
|
等待3秒钟后,再执行查询看看:
mysql> SELECT * FROM aaa;
+---------------------+
| timeline |
+---------------------+
| 2007-07-18 20:44:26 |
| 2007-07-18 20:44:27 |
| 2007-07-18 20:44:28 |
+---------------------+
2) 5天后清空test表:
1
|
CREATE ? EVENT e_test
|
2
|
? ON SCHEDULE? AT ? CURRENT_TIMESTAMP ? + INTERVAL 5? DAY
|
3
|
DO? TRUNCATE TABLE ? test.aaa;
|
3) 2007年7月20日12点整清空test表:
1
|
CREATE ? EVENT e_test
|
2
|
? ON SCHEDULE? AT ? TIMESTAMP ? '2007-07-20 12:00:00'
|
3
|
DO? TRUNCATE TABLE ? test.aaa;
|
4) 每天定时清空test表:
1
|
CREATE ? EVENT e_test
|
2
|
? ON SCHEDULE EVERY 1? DAY
|
3
|
DO? TRUNCATE TABLE ? test.aaa;
|
5) 5天后开启每天定时清空test表:
1
|
CREATE ? EVENT e_test
|
2
|
? ON SCHEDULE EVERY 1? DAY
|
3
|
STARTS? CURRENT_TIMESTAMP + INTERVAL 5? DAY
|
4
|
DO? TRUNCATE TABLE ? test.aaa;
|
6) 每天定时清空test表,5天后停止执行:
1
|
CREATE ? EVENT e_test
|
2
|
? ON SCHEDULE EVERY 1? DAY
|
3
|
ENDS? CURRENT_TIMESTAMP + INTERVAL 5? DAY
|
4
|
DO? TRUNCATE TABLE ? test.aaa;
|
7) 5天后开启每天定时清空test表,一个月后停止执行:
1
|
CREATE ? EVENT e_test
|
2
|
? ON SCHEDULE EVERY 1? DAY
|
3
|
STARTS? CURRENT_TIMESTAMP + INTERVAL 5? DAY
|
4
|
ENDS? CURRENT_TIMESTAMP + INTERVAL 1? MONTH
|
5
|
DO? TRUNCATE TABLE ? test.aaa;
|
[ON COMPLETION [NOT] PRESERVE]可以设置这个事件是执行一次还是持久执行,默认为NOT PRESERVE。
8) 每天定时清空test表(只执行一次,任务完成后就终止该事件):
1
|
CREATE ? EVENT e_test
|
2
|
? ON SCHEDULE EVERY 1? DAY
|
3
|
? ON COMPLETION? NOT ? PRESERVE
|
4
|
DO? TRUNCATE TABLE ? test.aaa;
|
[ENABLE | DISABLE]可是设置该事件创建后状态是否开启或关闭,默认为ENABLE。
[COMMENT ‘comment’]可以给该事件加上注释。
三、修改事件(ALTER EVENT)
1
|
ALTER ? EVENT event_name
|
2
|
[ ON SCHEDULE schedule]
|
3
|
[RENAME? TO new_event_name]
|
4
|
[ ON COMPLETION [ NOT ] PRESERVE]
|
5
|
[COMMENT? 'comment' ]
|
6
|
[ENABLE | DISABLE]
|
7
|
[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;
注意:如果你将event执行了Alter event event_name disable.那么当你重新启动mysql服务
器后,该event将被删除(测试版本:5.1.30)
应用案例
本案例是利用 event scheduler 的特性,每秒钟调用一次存储过程,用于判断 SLAVE 是否正常运行,如果发现 SLAVE 关闭了,忽略 0 次错误,然后重新启动 SLAVE。
* 首先创建存储过程
01
|
delimiter //
|
02
|
? create procedure ? `Slave_Monitor`()
|
03
|
? begin
|
04
|
? SELECT VARIABLE_VALUE? INTO ? @SLAVE_STATUS
|
05
|
? FROM information_schema.GLOBAL_STATUS
|
06
|
? WHERE VARIABLE_NAME= 'SLAVE_RUNNING' ;
|
07
|
IF ( 'ON' != @SLAVE_STATUS)? THEN
|
08
|
? SET GLOBAL ? SQL_SLAVE_SKIP_COUNTER=0;
|
09
|
SLAVE START;
|
10
|
? END IF;
|
11
|
? end ; //
|
12
|
delimiter ;
|
由于存储过程中无法调用类似 SHOW SLAVE STATUS 这样的语句,因此无法得到确切的复制错误信息和错误代码,不能进一步的处理 SLAVE 停止的各种情况。
* 接着,创建任务
1
|
CREATE ? EVENT IF NOT ? EXISTS `Slave_Monitor`
|
2
|
? ON SCHEDULE EVERY 5? SECOND
|
3
|
? ON COMPLETION PRESERVE
|
4
|
DO
|
5
|
CALL Slave_Monitor();
|
创建了一个任务,每 5秒钟执行一次,任务结束后依旧保留该任务,而不是删除。当然了,在本例中的任务不会结束,除非将它手动禁止了。
*
如果在运行中想要临时关闭一下某个任务,执行 ALTER EVENT 语句即可:
(root:localhost:)test> alter event `Slave_Monitor` ON
COMPLETION PRESERVE DISABLE;
(root:localhost:)test> alter event `Slave_Monitor` ON
COMPLETION PRESERVE ENABLE;
作者:zeo112140 发表于2013-8-13 13:55:52 原文链接
阅读:4 评论:0 查看评论
原文地址:[转]mysql创建定时任务, 感谢原作者分享。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.
