工作上,基本都是表的增删改查。与数据库的操作很多。为了数据安全,备份是必须要做的。
实现的逻辑:写了一个java的定时器,读取配置文件pro.properties中的 时间参数,在每天的 8点7分0秒 执行一次备份的bat命令。 24小时后再次执行
首先:java工程部分:
package xxx包;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import xx包.MyDate;
/*2014年1月13日 15:56:06
* 备份数据库的定时任务
* 执行cmd命令
*
*
* */
public class BackUpMysql {
private Timer timer;
private Date startDate;//启动时间
private long pollingInterval;//24*60*60*1000; //任务重复的间隔 设定为24小时
//构造函数
public BackUpMysql(Date date,long time) {
this.timer = new Timer();
this.startDate = date;
this.pollingInterval = time;
}
//主方法 启动定时器 ,
public void start(){
//设定在某个时间启动,然后反复执行
timer.schedule(new FileMonitor(),startDate,pollingInterval);
}
//定时器的执行任务对象 由 Timer 安排为一次执行或重复执行的任务
private class FileMonitor extends TimerTask {
public void run() {
//备份数据库的方法
String command = "cmd /k .\\config\\backupmysql.bat";
try {
Process child = Runtime.getRuntime().exec(command);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// child.waitFor();
}
}
//程序入口
public static void main(String[] args) {
Properties p = null;
InputStream in =null;
int hour = 0;
int min =1;
int second =0;
long delayTime = 1000*60*60*24;
try {
//读取配置文件
in = new BufferedInputStream(new FileInputStream(".\\config\\pro.properties"));
p = new Properties();
try {
p.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hour = Integer.parseInt(p.getProperty("hour"));
min = Integer.parseInt(p.getProperty("min"));
second = Integer.parseInt(p.getProperty("second"));
delayTime = (long)Integer.parseInt(p.getProperty("delayTime"));
BackUpMysql bkmysql = new BackUpMysql(MyDate.time(hour, min, second),delayTime);
bkmysql.start();
}
}
上面是主类和方法
用到一个时间类
package xxxxx;
/*
* 2013年12月18日 19:29:59
* 吴文付 时间戳*/
import java.util.Calendar;
import java.util.Date;
public class MyDate {
/*返回一个指定的时间*/
public static Date time(int day, int min,int second){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, day);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, second);
Date time = calendar.getTime();
return time;
}
}
备份mysql的bat文件如下:
@echo off
::获得时间戳 用来命名备份的文件夹
set FileTime=%date:~0,4%%date:~5,2%%date:~8,2%
::你的mysql bin目录
path "E:\\work\\APMServ-v5.2.6\\APMServ5.2.6\\MySQL5.1\\bin\\"
::创建备份文件存放的文件夹
md "e:\\3web\\php\\databaseBackUp"
md "e:\\3web\\php\\databaseBackUp\\"%FileTime%
::设置备份的数据保存的路径
set filepath="e:\\3web\\php\\databaseBackUp\\"%FileTime%"\\你取个名字.sql"
//这里 2个root 分别是用户名和密码
mysqldump -u root -proot --opt 库名 > %filepath%