Original: http://www.open-open.com/code/view/1447490829678
/**manipulating Databases*/ Public classbackupdb { PublicString Backup ()throwsioexception{String User= "Root";//user name of the databaseString Password = "admin";//password for the databaseString database = "Hrtweb";//the name of the database to be backed upDate Date =NewDate (); SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyymmddhhmmss"); String filepath= "d:\\" +sdf.format (date) + ". sql"; File File=NewFile ("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 ("Saved to" + filepath + "); } Catch(IOException e) {e.printstacktrace (); } returnfilepath; } }/**Creating Timers*/ Public classPicktask {PrivateTimer timer =NewTimer (); PrivateTimerTask task =NewTimerTask () { Public voidRun () {Date Date=NewDate (); SimpleDateFormat SDF=NewSimpleDateFormat ("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=Newbackupdb (); //Set backup Time if(Begintime.equals ("17:09")) { Try{bdb.backup ();//perform a file backupString dbName = Bdb.backup (). toString ();//Remove the backup file nameString Path = "d:\\"; intNameno = dbname.lastindexof ("\ \"); //determine if the file exists, if it exists, the backup succeeds, and if it does not, the backup does not succeed and needs to be backed up againFile File =NewFile (Path, dbname.substring (Nameno + 1, Dbname.length ())); if(File.exists ()) {System.out.println ("Backup succeeded"); }Else{System.out.println ("Backup failed, re-backup"); //Back up without a successful backup NewPicktask (). 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 yet, do not worry Oh!" "); } } }; //the Start method cannot be less, mainly the schedule method Public voidStartintDelayintInternal) {timer.schedule (task, Delay* 1000, Internal *); }}/**test class, perform scheduled backup instructions*/ Public classTimeruse { Public Static voidMain (string[] args) {picktask picktask=NewPicktask (); Picktask.start (1, 60);//executes once every 60 seconds }}
Java Scheduled BACKUP database