Search This Blog

2017/02/24

MySQL event scheduler

Attention: event_scheduler is supported after 5.1

Check if event_scheduler is on, execute:
SHOW VARIABLES LIKE 'event_scheduler';
To set event_scheduler on:
SET GLOBAL event_scheduler = ON;
or SET @@global.event_scheduler = ON;
or SET GLOBAL event_scheduler = 1;
or SET @@global.event_scheduler = 1;
To turn off is
SET GLOBAL event_scheduler = OFF;
or SET @@global.event_scheduler = OFF;
or SET GLOBAL event_scheduler = 0;
or SET @@global.event_scheduler = 0;

To create event:

CREATE EVENT [IF NOT EXISTS] event_name
  ON SCHEDULE schedule
  [ON COMPLETION [NOT] PRESERVE]
  [ENABLE | DISABLE]
  [COMMENT 'comment']
  DO sql_statement;
param
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}

Sample 1(insert 1 data every second):
CREATE EVENT test_event
ON SCHEDULE EVERY 1 SECOND 
DO INSERT INTO test_table VALUES (CURRENT_TIMESTAMP);
Sample 2(truncate table at a week late):
CREATE EVENT test_event
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 7 DAY
DO TRUNCATE TABLE test_table;
or in 2017-02-24 22:00:00:
CREATE EVENT test_event
ON SCHEDULE AT TIMESTAMP '2017-02-24 22:00:00'
DO TRUNCATE TABLE test_table;
or everyday:
CREATE EVENT test_event
ON SCHEDULE EVERY 1 DAY
DO TRUNCATE TABLE test_table;

To 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]
Sample 1 (disable event):
ALTER EVENT test_event DISABLE;

To delete event:

DROP EVENT [IF EXISTS] event_name
Sample 1 (disable event):
ALTER EVENT test_event DISABLE;

No comments :

Post a Comment