Home Database Mysql Tutorial [转]mysql创建定时任务

[转]mysql创建定时任务

Jun 07, 2016 pm 04:38 PM
mysql Task create Preface add timing

一、前言 自 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创建定时任务

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles