Java App for PostgreSQL scheduled backups using pg_dump (Windows only)
Database backups are an essential part of system maintenance, ensuring data can be recovered in the event of a failure.
In this post, I'll show you how to automate PostgreSQL backups using a simple Java application.
The application generates a backup file named with the current date by interacting with PostgreSQL’s pg_dump
utility.
Note
This approach works on Windows systems and assumes the availability of pg_dump.exe and its dependencies.
Automating PostgreSQL backups with Java on demand
- Generate a Filename: Create a filename with the current date to organize backups.
- Check for Existing Files: Ensure there are no duplicate files or delete older versions.
- Run pg_dump: Execute the
pg_dump
command with appropriate parameters to create a backup.
Here is the complete Java code:
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class PostgreSQLBackup {
public void backupPGSQL() {
try {
// Define paths and PostgreSQL details
String backupDirPath = "C:\\BACKUPS\\";
String pgDumpPath = "C:\\Program Files\\PostgreSQL\\bin\\pg_dump.exe";
//PostgreSQL variables
String ip = "192.168.1.1";
String user = "postgres";
String database = "yourDatabase";
String password = "yourPassword";
// Generate filename with today’s date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String date = dateFormat.format(new Date());
String backupFile = backupDirPath + date + ".backup";
// Ensure the backup directory exists
File backupDir = new File(backupDirPath);
if (!backupDir.exists() && !backupDir.mkdirs()) {
throw new IOException("Could not create backup directory: " + backupDirPath);
}
// Delete any previous backup that might exist
File backup = new File(backupFile);
if (backup.exists()) {
backup.delete();
}
// Configure ProcessBuilder for pg_dump
ProcessBuilder pb = new ProcessBuilder(
pgDumpPath,
"-f", backupFile,
"-F", "c",
"-Z", "9",
"-v",
"-h", ip,
"-U", user,
database
);
pb.environment().put("PGPASSWORD", password);
pb.redirectErrorStream(true);
// Start the process and capture output
Process process = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} finally {
reader.close();
}
// Wait for process to complete
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("pg_dump failed with exit code: " + exitCode);
}
System.out.println("Backup completed successfully: " + backupFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new PostgreSQLBackup().backupPGSQL();
}
}
Key Points
- Replace
ip
,user
,database
, andpassword
variables with your PostgreSQL server details. - Ensure
pg_dump.exe
(and required DLL files) is available atpgDumpPath
or update the path accordingly. - The
PGPASSWORD
environment variable is used to pass the password securely topg_dump
. - The backup file is saved in the
backupDirPath
directory with the formatyyyyMMdd.backup
. - The process output is captured and printed to the console for monitoring.
Automating PostgreSQL backups with Java on a schedule
To run the backup automatically every day, you can use a TimerTask
in Java:
import java.util.*;
public class ScheduledBackup {
public static void main(String[] args) {
TimerTask backupTask = new TimerTask() {
@Override
public void run() {
new PostgreSQLBackup().backupPGSQL();
}
};
// Schedule the task to run every 24 hours (at 1:00 AM)
Timer timer = new Timer();
Calendar taskTime = Calendar.getInstance();
taskTime.set(Calendar.HOUR_OF_DAY, 1);
taskTime.set(Calendar.MINUTE, 0);
taskTime.set(Calendar.SECOND, 0);
// Adjust start time if it's already past the initial scheduled time
if (new Date().after(taskTime.getTime())) {
taskTime.add(Calendar.DAY_OF_YEAR, 1);
}
timer.scheduleAtFixedRate(backupTask, taskTime.getTime(), 1000L * 60 * 60 * 24);
System.out.println("Scheduled backup task set for 1:00 AM daily.");
}
}
Notes
- You can configure the scheduled time by adjusting the
Calendar.HOUR_OF_DAY
value. - For production systems, consider external schedulers like cron on Linux or the Task Scheduler on Windows.
Conclusion
Automating PostgreSQL backups with a Java application provides flexibility and allows integration with other tools.
While this guide focuses on pg_dump
, you can extend the solution to include notifications, logging, and error handling to suit your needs.
Remember to always protect your backup files and credentials to ensure data security and integrity.
Comments in "Java App for PostgreSQL scheduled backups using pg_dump (Windows only)"