一、创建定时任务
1、确保MySQL的事件调度器已经开启。可以通过以下SQL命令检查是否开启:
SHOW VARIABLES LIKE 'event_scheduler';
2、如果返回的值为OFF,则可以通过以下命令开启事件调度器:
SET GLOBAL event_scheduler = ON;
3、以下是一个删除your_table
表中7天前数据的示例:
CREATE EVENT IF NOT EXISTS event_cleanup_data
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_TIMESTAMP
DO
DELETE FROM your_table WHERE your_date_column < DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY);
4、启动事件
ALTER EVENT event_cleanup_data ON
COMPLETION PRESERVE ENABLE;
确保替换your_table
和your_date_column
为你实际的表名和列名。这样,你就设置了一个定期清理数据的任务
5、查看事件
SHOW EVENTS;
二、实例一:删除apb项目中系统日志表中指定90天的数据
CREATE EVENT IF NOT EXISTS event_cleanup_abplog
ON SCHEDULE EVERY 1 DAY
STARTS '2024-08-14 23:00:00'
DO
BEGIN
DELETE FROM abpauditlogs WHERE executiontime < DATE_SUB(CURRENT_DATE, INTERVAL 90 DAY);
DELETE FROM abpauditlogactions WHERE executiontime < DATE_SUB(CURRENT_DATE, INTERVAL 90 DAY);
DELETE FROM abpentitychanges WHERE changetime < DATE_SUB(CURRENT_DATE, INTERVAL 90 DAY);
END;