Java timed backup database java database timed backup, mysql is used as an example here:
BackupDb. java (database backup class)
Public class BackupDb {
Public String backup () throws IOException {
String user = "root ";// User name of the database
String password = "root"; // database password
String database = "database"; // name of the database to be backed up
Date date = new Date ();
SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss ");
String filepath = "d: // jinsus" + sdf. format (date) + ". SQL ";
File file = new File ("d: //", "jinsus" + 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(cmd.exe c (stmt1 );
System. out. println ("saved to" + filepath + ");
} Catch (IOException e ){
E. printStackTrace ();
}
Return filepath;
}
}
TimerUse. java (timing and test class)
Public class TimerUse {
Public static void main (String [] args ){
PickTask picktask = new PickTask ();
Picktask. start (1, 60); // execute once every 60 seconds
}
}
Class PickTask {
Private Timer timer;
PrivateTimerTask 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 ("Start time:" + beginDate );
BackupDb bdb = new BackupDb ();
// Set the backup time
If (beginTime. equals ("16:39 ")){
Try {
Bdb. backup (); // execute file backup
String dbName = bdb. backup (). toString (); // Retrieve the name of the backup file
String path = "d ://";
Int nameNo = dbName. lastIndexOf ("//");
// Determine whether the file exists. If yes, the backup is successful. If no, the backup is unsuccessful and you need to back up the file again.
File file = new File (path, dbName. substring (nameNo + 1,
DbName. length ()));
If (file. exists ()){
System. out. println ("backup successful ");
} Else {
System. out. println ("backup failed, backup again ");
// Backup again if the backup fails
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 ("The time is not enough. Don't worry! ");
}
}
};
// StartThe number of methods is not small, mainly the schedule method.
Public void start (int delay, int internal ){
Timer. schedule (task, delay * 1000, internal * 1000 );
}
}