命题: 每日 02:00 am 定时删除 表 t (id int primary key,ptime TIMESTAMP DEFAULT CURRENT_TIMESTAMP) 中三天以前的记录。
=======================================方法一:操作系统=======================================(Windows)在WINDOWS 操作系统中 的计划任务中定时操作, 进入WINDOWS的命令行, (开始->运行-> 输入 cmd 回车)
C:\>at 02:00 /every:M,T,W,Th,F,S,Su "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysql.exe" -u root -p123 csdn -e "delete from t where ptime <date_sub(curdate(),interval 3 day)"
Added a new job with job ID = 1C:\>atStatus ID Day Time Command Line------------------------------------------------------------------------------- 1 Each Monday... 上午 02:00 "C:\Program Files\MySQL\MySQLServer 5.1\bin\mysql.exe" -u root -p123 csdn -e "delete from t where ptime <date_sub(curdate(),interval 3 day)"C:\>
linux
1、创建backup.sh文件#!/bin/shexport MYSQLBAKDATE=`date +%Y%m%d`# echo $MYSQLBAKDATEexport OUTFILE=$MYSQLBAKDATE'.TestDB.dbf'# echo $OUTFILErm -f /bak/$OUTFILE/usr/local/mysql/bin/mysqldump -uroot -p****** -R TestDB > /bak/$OUTFILEgzip /bak/$OUTFILE#END如果考虑得再周全点,可以考虑删除一个星期或一个月之前的备份文件。2、使用crontab -e命令编辑计划任务,加入以下一条记录30 02 * * * sh /usr/local/mysql/backup.sh表示在凌晨2点30分做备份
=======================================方法二:MySQL事件 Event=======================================
MySQL 5.1.6 之后,你可以直接使用类似于oralce job的mysql event首先,检查一下你的MYSQL是否打开了这项功能。mysql> show variables like '%sc%';+-----------------+-------+| Variable_name | Value |+-----------------+-------+| event_scheduler | OFF |+-----------------+-------+1 row in set (0.00 sec)
默认下是未打开的,你可以到 my.ini (windows)/ my.cnf (linux/unix) 参数文件中定义后重启mysqld或者直接 set global event_scheduler=on;
mysql> show variables like '%sc%';+-----------------+-------+| Variable_name | Value |+-----------------+-------+| event_scheduler | ON |+-----------------+-------+1 row in set (0.00 sec)
创建这个eventmysql> CREATE EVENT myevent -> ON SCHEDULE EVERY 1 DAY STARTS '2009-10-24 02:00:00' -> DO -> delete from t where ptime <date_sub(curdate(),interval 3 day);Query OK, 0 rows affected (0.09 sec)mysql> show events;+------+---------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+--| Db | Name | Definer | Time zone | Type | Execute at | Interval value | Interval field | Starts | Ends | Status | O+------+---------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+--| csdn | myevent | root | SYSTEM | RECURRING | NULL | 1 | DAY | 2009-10-24 02:00:00 | NULL | ENABLED | +------+---------+----------------+-----------+-----------+------------+----------------+----------------+---------------------+------+---------+--1 row in set (0.00 sec)mysql>
关于EVENT的介绍(很遗憾,没有中文版的)19.4. Using the Event Scheduler19.4.1. Event Scheduler Overview 19.4.2. Event Scheduler Configuration 19.4.3. Event Syntax 19.4.4. Event Metadata 19.4.5. Event Scheduler Status 19.4.6. The Event Scheduler and MySQL Privileges 关于create event 的语法和例子。12.1.11. CREATE EVENT Syntax