Java App for PostgreSQL scheduled backups using pg_dump (Windows only)
Today I'll show you an easy way to automate your database backup dumps with a java application that runs on the background. This simple app will generate a backup of your database and will name it with today's date. It's not really the java program interacting with the database, but the app interacting with the command line program pg_dump.
The procedure is quite simple. First, we generate a filename with today's date. Then we check if the file exists. Finally, we call the pg_dump with the appropriate parameters and the backup is generated
public void backupPGSQL() {
try{
Runtime r = Runtime.getRuntime();
//Path to the place we store our backup
String rutaCT = "C:\\\\BAKCUPS\\\\";
//PostgreSQL variables
String IP = "192.168.1.1";
String user = "postgres";
String dbase = "yourDataBase";
String password = "yourPassword";
Process p;
ProcessBuilder pb;
InputStreamReader reader;
BufferedReader buf_reader;
String line;
//We build a string with today's date (This will be the backup's filename)
java.util.TimeZone zonah = java.util.TimeZone.getTimeZone("GMT+1");
java.util.Calendar Calendario = java.util.GregorianCalendar.getInstance( zonah, new java.util.Locale("es"));
java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyyMMdd");
StringBuffer date = new StringBuffer();
date.append(df.format(Calendario.getTime()));
java.io.File file = new java.io.File(rutaCT);
// We test if the path to our programs exists
if (file.exists()) {
// We then test if the file we're going to generate exist too. If so we will delete it
StringBuffer fechafile = new StringBuffer();
fechafile.append(rutaCT);
fechafile.append(date.toString());
fechafile.append(".backup");
java.io.File ficherofile = new java.io.File(fechafile.toString());
if (ficherofile.exists()) {
ficherofile.delete();
}
r = Runtime.getRuntime();
pb = new ProcessBuilder(rutaCT + "pg_dump.exe", "-f", fechafile.toString(),
"-F", "c", "-Z", "9", "-v", "-o", "-h",IP, "-U", user, dbase);
pb.environment().put("PGPASSWORD", password);
pb.redirectErrorStream(true);
p = pb.start();
try {
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String ll;
while ((ll = br.readLine()) != null) {
System.out.println(ll);
}
} catch (IOException e) {
log("ERROR "+e.getMessage(), e);
}
}
} catch(IOException x) {
System.err.println("Could not invoke browser, command=");
System.err.println("Caught: " + x.getMessage());
}
}
To run the above method you will need to have pg_dump.exe
and the necessary dll files in the backups directory.
We can also schedule the task to be run once a day so we can have a fresh backup every night:
TimerTask backupTask = new TimerTask() {
public void run(){
backupPGSQL();
}
};
// We schedule the task to be run every 24 hours
Timer time = new Timer();
time.scheduleAtFixedRate(backupTask, new Date(),1000*60*60*24);
// Even better, we can schedule the task to be run every 24 hours at a fixed time.
// (remember to remove the above line if you prefer this method)
Calendar taskTime = Calendar.getInstance();
// We want the task to be run at 1 o'clock in the morning
taskTime.set(Calendar.HOUR_OF_DAY, 1);
// We clear the rest of the values for the calendar
taskTime.clear(Calendar.MINUTE);
taskTime.clear(Calendar.SECOND);
taskTime.clear(Calendar.MILLISECOND);
// If the time has already passed, we add another day to the count, so the task will start tomorrow
if (now.after(taskTime)) {
taskTime.add(Calendar.DAY_OF_YEAR, 1);
}
Date startingDate = taskTime.getTime();
time.scheduleAtFixedRate(backupTask, startingDate, 1000L*60*60*24);
Comments in "Java App for PostgreSQL scheduled backups using pg_dump (Windows only)"