1. Requirements: from 10:00 p.m. to 5:00 a.m. every day, execute the stored procedure regularly every 10 minutes.
2. Implementation mode: there are two ways to achieve it:
One is more conventional. Using mysql event timing task, first introduce the related commands of event timing task in mysql,
To see if event is enabled:
- SELECT @@event_scheduler;
- SHOW VARIABLES LIKE 'event%';
To start a scheduled task:
- set GLOBAL event_scheduler = 1;
- SET GLOBAL event_scheduler = ON;
To establish a scheduled task:
- DROP EVENT IF EXISTS JOB_ALARM;
- CREATE EVENT JOB_ALARM
- ON SCHEDULE EVERY 10 MINUTE
- DO
- BEGIN
- if(date_format(current_time(),'%H')>22 || date_format(current_time(),'%H')<5) THEN
- CALL PRO_ALARM();
- END IF;
- END
To establish a stored procedure:
- DROP PROCEDURE IF EXISTS PRO_ALARM;
- CREATE PROCEDURE PRO_ALARM()
- BEGIN
- DECLARE userId VARCHAR(32);
- #This is used to handle the cursor reaching the last row
- DECLARE s INT DEFAULT 0;
- #Declare cursor "cursor" name (cursor "name is a multi row result set)
- DECLARE cursor_data CURSOR FOR
- SELECT tmp.USER_ID
- FROM (
- SELECT
- e.USER_ID,
- MAX(e.TIME_GMT) TIME_GMT
- FROM EVENTS e
- GROUP BY e.USER_ID
- HAVING MAX(e.TIME_GMT) < UNIX_TIMESTAMP() - 60 * 30
- AND MAX(e.TIME_GMT) > UNIX_TIMESTAMP() - 60 * 60 * 24) tmp
- INNER JOIN EVENTS t ON tmp.USER_ID = t.USER_ID
- AND tmp.TIME_GMT = t.TIME_GMT
- WHERE TYPE_ID != '34001';
- #Set a termination flag
- DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET s = 1;
- OPEN cursor_data;
- #Get the record of the current cursor pointer, read a row of data and pass it to variables A and B
- FETCH cursor_data
- INTO userId;
- #Start the loop to determine whether the cursor has reached the end as a loop condition
- WHILE s <> 1 DO
- INSERT INTO EVENTS_NOTIFICATION VALUES (NULL, SYSDATE(), UNIX_TIMESTAMP(SYSDATE()),
- UNIX_TIMESTAMP(SYSDATE()), '00000', userId, '1', '0');
- #Read data from next row
- FETCH cursor_data
- INTO userId;
- END WHILE;
- #Close cursor
- CLOSE cursor_data;
- END;
There are some limitations when configuring timers, and since mysql used by bloggers enables skip grant tables, when setting event on, it always reports an error, so the second implementation method is proposed. The specific error information is as follows:
- [HY000][1290] The MySQL server is running with the --event-scheduler=DISABLED or --skip-grant-tables option so it cannot execute this statement
The second way is to use the timing task of linux,
Basic command of linux timing task:
View scheduled tasks: crontab -l
Edit scheduled task: crontab -e
* / 10 22-23,0-5 * * mysql -u user name - p password - e "use db_name;CALL PRO_ALARM();"
Or save use db_name;CALL PRO_ALARM(); in the sql script. The editing timing task is as follows:
* / 10 22-23,0-5 * * mysql -u user name - p password < / application / job_mysql.sql