A logo showing the text blog.marcnuri.com
Español
Home»Java»Java App for PostgreSQL scheduled backups using pg_dump (Windows only)

Recent Posts

  • MCP Tool Annotations: Adding Metadata and Context to Your AI Tools
  • Fabric8 Kubernetes Client 7.2 is now available!
  • Connecting to an MCP Server from JavaScript using AI SDK
  • Connecting to an MCP Server from JavaScript using LangChain.js
  • The Future of Developer Tools: Adapting to Machine-Based Developers

Categories

  • Artificial Intelligence
  • Front-end
  • Go
  • Industry and business
  • Java
  • JavaScript
  • Legacy
  • Operations
  • Personal
  • Pet projects
  • Tools

Archives

  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • August 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • February 2020
  • January 2020
  • December 2019
  • October 2019
  • September 2019
  • July 2019
  • March 2019
  • November 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • December 2017
  • July 2017
  • January 2017
  • December 2015
  • November 2015
  • December 2014
  • March 2014
  • February 2011
  • November 2008
  • June 2008
  • May 2008
  • April 2008
  • January 2008
  • November 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007

Java App for PostgreSQL scheduled backups using pg_dump (Windows only)

2007-03-27 in Java / Legacy tagged Backup / cron / Database / Java / PostgreSQL / Windows by Marc Nuri | Last updated: 2025-01-28
Versión en Español

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

  1. Generate a Filename: Create a filename with the current date to organize backups.
  2. Check for Existing Files: Ensure there are no duplicate files or delete older versions.
  3. Run pg_dump: Execute the pg_dump command with appropriate parameters to create a backup.

Here is the complete Java code:

PostgreSQLBackup.java
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, and password variables with your PostgreSQL server details.
  • Ensure pg_dump.exe (and required DLL files) is available at pgDumpPath or update the path accordingly.
  • The PGPASSWORD environment variable is used to pass the password securely to pg_dump.
  • The backup file is saved in the backupDirPath directory with the format yyyyMMdd.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:

ScheduledBackup.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.

Twitter iconFacebook iconLinkedIn iconPinterest iconEmail icon

Comments in "Java App for PostgreSQL scheduled backups using pg_dump (Windows only)"

  • Avatar for Araz
    Araz
    2008-08-19 08:33
    Thank you very much..
  • Avatar for lukasz
    lukasz
    2009-03-28 14:28
    Thanks. Work good ;-)
  • Avatar for Rupendra
    Rupendra
    2010-11-23 18:08
    Thank you very much. It worked and will help me a lot in automating a set of tedious tasks.
  • Avatar for Blanka
    Blanka
    2012-11-14 09:54
    Sir. Best tit. I mean tut. Thanks crap..love it shit bro :)
  • Avatar for Deepali
    Deepali
    2013-10-14 09:57
    It's fantastic, I was in search of this, I would try my best to work on this. Please be kind to help me if I have any queries. :)
  • Avatar for fayez
    fayez
    2013-12-02 02:06
    really really ... you are great thnxxxxxxxxxxxxxxxxxx
  • Avatar for csjawad
    csjawad
    2014-06-06 14:13
    Weldone Sir.
  • Avatar for Codemonkey
    Codemonkey
    2014-09-26 14:48
    I used snippets of your code in my project and they works great. Thank you.
  • Avatar for utpal
    utpal
    2015-05-11 07:32
    please help me, how i run this above code in netbeans.

Post navigation
Displaying a jTable inside another jTable // JTable cellRendererChoosing a printer programmatically in Jasper Reports
© 2007 - 2025 Marc Nuri