Implementation of mysql timing task
https://blog.csdn.net/erdongritian/article/details/53158617
1. Requirements: Every 10 pm to 5 am, the stored procedure is executed regularly every 10 minutes.
2. Implementation: There are two implementations:
One is more conventional, using the event timing task of mysql, first introduce the relevant commands of the event timing task in mysql,
Check if event is enabled:
- SELECT @@event_scheduler;
- SHOW VARIABLES LIKE'event%';
To start a scheduled task:
- setGLOBAL event_scheduler = 1;
- SETGLOBAL event_scheduler = ON;
Create 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
Create a stored procedure:
- DROPPROCEDURE IF EXISTS PRO_ALARM;
- CREATEPROCEDURE PRO_ALARM()
- BEGIN
- DECLARE userId VARCHAR(32);
- #This is used to handle the case where the cursor reaches the last row
- DECLARE s INTDEFAULT 0;
- #declare cursor cursor_name (cursor_name is a multi-row result set)
- DECLARE cursor_data CURSORFOR
- 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';
- #设置一个终止标记
- DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET s = 1;
- OPEN cursor_data;
- #获取游标当前指针的记录,读取一行数据并传给变量a,b
- FETCH cursor_data
- INTO userId;
- #开始循环,判断是否游标已经到达了最后作为循环条件
- WHILE s <> 1 DO
- INSERT INTO EVENTS_NOTIFICATION VALUES (NULL, SYSDATE(), UNIX_TIMESTAMP(SYSDATE()),
- UNIX_TIMESTAMP(SYSDATE()), '00000', userId, '1', '0');
- #读取下一行的数据
- FETCH cursor_data
- INTO userId;
- END WHILE;
- #关闭游标
- CLOSE cursor_data;
- END;
在配置定时器时有一些局限性,并且由于博主使用的mysql启用了skip-grant-tables,在设置event开启时,总是报错,所以想到了第二种实现方式,具体报错信息如下:
- [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 to achieve this is to use linux's timed tasks,
Basic commands for linux timed tasks:
View scheduled tasks: crontab -l
Edit scheduled tasks: crontab -e
*/10 22-23,0-5 * * * mysql -u username -p password -e "use db_name;CALL PRO_ALARM();"
Or save use db_name;CALL PRO_ALARM(); to the sql script, and edit the scheduled task as follows:
*/10 22-23,0-5 * * * mysql -u username -p password < /application/Job_mysql.sql