java 定時備份數據庫
/**
操作數據庫
*/
public class BackupDb {
public String backup() throws IOException{
String user = "root"; //數據庫的用戶名
String password = "admin";//數據庫的密碼
String database = "hrtweb";//要備份的數據庫名
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String filepath = "d:\\"+sdf.format(date)+".sql";
File file = new File("d:\\",sdf.format(date)+".sql");
if(!file.exists()){
file.createNewFile();
}
String stmt1 = "mysqldump " + database +" -h 127.0.0.1 "+ " -u " + user + " -p" +
password + " --default-character-set=gbk --result-file=" + filepath;
try {
Runtime.getRuntime().exec(stmt1);
System.out.println("已經保存到 " + filepath + " 中");
} catch (IOException e) {
e.printStackTrace();
}
return filepath;
}
}
/**
創建定時器
*/
public class PickTask {
private Timer timer = new Timer();
private TimerTask task = new TimerTask() {
public void run() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String beginDate = sdf.format(date);
String beginTime = beginDate.substring(11, 16);
System.out.println("開始時間:"+beginDate);
BackupDb bdb = new BackupDb();
// 設定備份時間
if (beginTime.equals("17:09")) {
try {
bdb.backup(); // 執行文件備份
String dbName = bdb.backup().toString(); // 取出備份的文件名字
String path = "d:\\";
int nameNo = dbName.lastIndexOf("\\");
//判斷文件是否存在,如果存在,則備份成功,如果不存在則備份不成功需要重新備份
File file = new File(path, dbName.substring(nameNo + 1,dbName.length()));
if (file.exists()){
System.out.println("備份成功");
}else{
System.out.println("備份失敗,重新備份");
//在備份未成功的情況下重新備份
new PickTask().start(1, 1);
}
} catch (FileNotFoundException e) {
System.out.println("can not find the file");
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("時間還不到呢,不要著急哦!");
}
}
};
//start 方法不能少,主要是schedule方法
public void start(int delay, int internal) {
timer.schedule(task, delay * 1000, internal * 1000);
}
}
/**
測試類,執行定時備份指令
*/
public class TimerUse {
public static void main(String[] args) {
PickTask picktask = new PickTask();
picktask.start(1, 60); // 每60秒執行一次
}
}