MySQL的計劃任務創建 實際項目中只想將最近7天的記錄保存在MySQL數據庫中,使用程序通過SQL指令的方式刪除比較麻煩且效率低,用Mysql 提供的事件調度器(event scheduler)可輕松實現。 www.2cto.com 具體步驟如下: 1:超級用戶方式登陸MySQL console # mysql -uroot 2:打開event_scheduler(默認是關掉的) mysql> set global event_scheduler = ON; 3:創建我們的事件(本例中命名為delete_old_record) www.2cto.com mysql> CREATE EVENT delete_old_record ON SCHEDULE EVERY 1 DAY STARTS NOW() DO -- delete the old records of demo_1_table DELETE FROM demo_1_table WHERE datediff(NOW(),log_timestamp)>=7; -- delete the old records of puma_2_table DELETE FROM demo_2_table WHERE datediff(NOW(),log_timestamp)>=7; -- delete the old records of puma_3_table DELETE FROM demo_3_table WHERE datediff(NOW(),log_timestamp)>=7; -- delete the old records of puma_4_table DELETE FROM demo_4_table WHERE datediff(NOW(),log_timestamp)>=7; 4:啟動創建的事件 mysql> ALTER EVENT delete_old_record ENABLE; 這樣以後,數據庫就會每天執行DO後面的作業,刪除各個table中7天之前的記錄。 附錄:CREATE EVENT的格式如下: CREATE [DEFINER = { user | CURRENT_USER }] EVENT [IF NOT EXISTS] event_name ON SCHEDULE schedule [ON COMPLETION [NOT] PRESERVE] [ENABLE | DISABLE | DISABLE ON SLAVE] [COMMENT 'comment'] DO event_body; schedule: AT timestamp [+ INTERVAL interval] ... | EVERY interval [STARTS timestamp [+ INTERVAL interval] ...] [ENDS timestamp [+ INTERVAL interval] ...] interval: quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE | WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE | DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}