Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7730267
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T06:10:56+00:00 2026-06-01T06:10:56+00:00

Not much code since I’m a bit at a loss on how to start.

  • 0

Not much code since I’m a bit at a loss on how to start.

I’m trying to create an application that backs up a Derby database and stores the users data. I have the code for the backup itself that can be run manually. I want to create a feature that will check a settings file, and execute a backup at the proper schedule (daily, weekly, monthly). I think I can make it check on start up, but there’s an issue if the application is running, I’d like it to periodically check the time. There’s a good possibility that this application will be left running for days on end.

I also want to allow the users to “sleep” the backup for a few hours if there scheduled time has come.

I can have a Thread.Sleep() called at bootup and have it check every X minute/hours. Similarly if they choose to sleep the backup. I’m not sure if that’s the best way to do it. I assume any API call will probably do the same, but I’m wondering if I’m missing something in handling a thread like that.

Are there any functions/libraries in the Netbeans IDE & Platform that I’m leveraging, that I could hook into to help me build this functionality?

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T06:10:58+00:00Added an answer on June 1, 2026 at 6:10 am

    Here’s how I implemented it. I changed the method of implementation a bit, so this answer isn’t exactly how the question was worded. I removed the “sleep” feature, but using the code I’m providing you could easily implement it. I have it partially implemented, and I’ll show the code below. It basically involves creating a few classes that implement Runnable. The actual code to run the backup isn’t shown. That would be platform specific anyway, so handle it as you would. We’re using Derby, so that’s how our backups are handled.

    I’ll break it down by class & function:

    DatabaseBackupReminder. This class handles the prompt to the user that tells them how long since the last backup, and allows them to sleep the reminder for X number of hours. It is a thread itself, so it can be called somewhere else and slept too, so it’s not constantly pinging the DB to see when the last backup was run.

    public class DatabaseBackupReminder extends Thread
    
    /*****************Variables ****************/
    String backupFrequency; //How often to backup? Daily, Monthly, Weekly, or Never
    String backupTimeOfDay; //I don't use this, but the idea was to autobackup morning,  
                            //day, or night
    boolean backupIsSet = false;    //Have they set a schedule?
    Timestamp lastBackupRunTime; //Pulled from our Derby database to see when the backup was run
    Timestamp backupScheduleSetTime; //Pulled from the DB to see when the user set the schedule
                                    //This is so, if they set it to daily, we will check 24hrs from the set date for
                                    //backup validity
    Period periodSinceLastBackup; //Using the Joda library, we use this to calculate
    boolean backupEverRan; //We check to see if they've ever backed up
                                        //Useful logic for clear dialog purposes.
    public enum enumBackupFrequencies {DAILY, WEEKLY, MONTHLY, NEVER} //use a valueOf with the backupFrequency.
    //We're using java 1.7, no Switch on strings, this is a workaround
       Herd herd;//Herd is a custom datatype we use, it's basically a wrapper around a Derby table.
    /*******************methods***************************************/                                     
        public DatabaseBackupReminder(String backupFrequency, String backupTimeOfDay, Timestamp lastBackupRunTime, Timestamp backupScheduleSetTime, Herd herd) 
        //Constructor
        //Herd is a custom datatype we use, it's basically a wrapper around a Derby table.
        boolean getBackupStillValid() //Checks based on lastBackupRunTime, and backupEverRan to see
        //if we have a valid backup
    
        public void promptForBackup(Period duration, boolean backupEverRunx) 
            //Take's the duration & has it ever run and displays a message.
            //Something like "It's been 2 weeks, 1 days since your last backup"
            //Not fully implemented, this was scrapped, but I'll explain how I think it should have worked below
    
        public void run()
        //Main thread for this reminder
        public String timeSinceLastBackupString()
        //Calls it based on objects values, not specific values, see method below
        public String timeSinceLastBackupString(Period duration, boolean backupEverRunx)
        //Constructs the string used in promptForBackup
    
    
    
    /********full method code**********/
    public DatabaseBackupReminder(String backupFrequency, String backupTimeOfDay, Timestamp lastBackupRunTime, Timestamp backupScheduleSetTime, Herd herd) {
        this.herd = herd;
        if (backupFrequency == null) {
            backupFrequency = "";
        }
        if (backupTimeOfDay == null) {
            backupTimeOfDay = "";
        }
        if (backupScheduleSetTime == null) {
            this.backupScheduleSetTime = new Timestamp(0);
        } else {
            this.backupScheduleSetTime = backupScheduleSetTime;
        }
        this.backupFrequency = backupFrequency;
        this.backupTimeOfDay = backupTimeOfDay;
        if (lastBackupRunTime == null) {
            this.lastBackupRunTime = new Timestamp(0);
        } else {
            this.lastBackupRunTime = lastBackupRunTime;
        }
        periodSinceLastBackup = new Period(this.lastBackupRunTime.getTime(), Calendar.getInstance().getTimeInMillis());
        if (backupFrequency.trim().length() > 1) {
            backupIsSet = true;
        }
        backupEverRan = false;
        if (this.lastBackupRunTime.getTime() != 0) {
            backupEverRan = true;
        }
    }
    
     boolean getBackupStillValid() {
        if (lastBackupRunTime.getTime() > 0) {
            backupEverRan = true;
    
        } else {
            return false;
        }
        if (backupFrequency.trim().length() > 1) {
            backupIsSet = true;
    
        }
    
    
        if (backupIsSet) {
            switch (enumBackupFrequencies.valueOf(backupFrequency.trim().toUpperCase())) {
                case DAILY:
                    if (periodSinceLastBackup.getYears() > 1 || periodSinceLastBackup.getMonths() > 1 || periodSinceLastBackup.getWeeks() > 1 || periodSinceLastBackup.getDays() >= 1) {
    
                        return false;
                    }
                    break;
                case WEEKLY:
                    if (periodSinceLastBackup.getYears() > 1 || periodSinceLastBackup.getMonths() > 1 || periodSinceLastBackup.getWeeks() >= 1) {
                        return false;
    
                    }
                    break;
                case MONTHLY:
                    if (periodSinceLastBackup.getYears() > 1 || periodSinceLastBackup.getMonths() >= 1) {
                        return false;
    
                    }
                    break;
                case NEVER:
            }
        }
        if (backupEverRan) {
            return true;
        } else {
            return false;
        }
    
    }
    
    public void run() {
    
        if (backupIsSet) {
            switch (enumBackupFrequencies.valueOf(backupFrequency.trim().toUpperCase())) {
                case DAILY:
                    if (periodSinceLastBackup.getYears() > 1 || periodSinceLastBackup.getMonths() > 1 || periodSinceLastBackup.getWeeks() > 1 || periodSinceLastBackup.getDays() > 1) {
    
                        promptForBackup(periodSinceLastBackup, backupEverRan);
    
                    }
                    break;
                case WEEKLY:
                    if (periodSinceLastBackup.getYears() > 1 || periodSinceLastBackup.getMonths() > 1 || periodSinceLastBackup.getWeeks() > 1) {
                        promptForBackup(periodSinceLastBackup, backupEverRan);
    
                    }
                    break;
                case MONTHLY:
                    if (periodSinceLastBackup.getYears() > 1 || periodSinceLastBackup.getMonths() > 1) {
                        promptForBackup(periodSinceLastBackup, backupEverRan);
    
                    }
                    break;
                case NEVER:
            }
        }
    
    
    
    }
    public void promptForBackup(Period duration, boolean backupEverRun) {
        int response;
        long delay = 0;
    
        response = JOptionPane.showConfirmDialog(null, timeSinceLastBackupString(duration, backupEverRun));
        if (response == JOptionPane.NO_OPTION) {
            //TODO: open "how long to remind" dialog
            BackupSnoozePanel snoozePanel = new BackupSnoozePanel();
    
            JOptionPane.showMessageDialog(null, snoozePanel);
    
            switch (snoozePanel.BackupDelayInterval.getSelectedIndex()) {
                case 0:
                    delay = 5000; //5 seconds, for testing
                    //delay = 60 * 60 * 1000; // 1 hour
                    break;
                case 1:
                    delay = 10000; //10 seconds, for testing
                    //delay = 4 * 60 * 60 * 1000; // 4 hours
                    break;
                case 2:
                    delay = 15000; //15 seconds, for testing
                    //delay = 8 * 60 * 60 * 1000; // 8 hours
                    break;
                case 3:
                    delay = 20000; //20 seconds, for testing
                    ///delay = 12 * 60 * 60 * 1000; // 12 hours
                    break;
                case 4:
                    delay = 0; //next boot
                    break;
            }
    
    
        } else {
            //TODO: run backup    
        }
        try {
    
            if (delay > 0) {
            //TODO: Code to sleep this reminder. Thread.sleep(delay) probably
    
            }
        } catch (Exception ex) {
            //TODO: something to handle exceptions
        }
    
    }//end promptForBackup
    
     public String timeSinceLastBackupString(Period duration, boolean backupEverRunx) {
    
        if (!backupEverRunx) {
            return "The backup has never been run. Would you like to run one?";
        }
    
    
        String durationString = "It has been ";
        if (duration.getYears() >= 1) {
            durationString += duration.getYears() + " years";
        }
        if (duration.getMonths() >= 1) {
            durationString += duration.getMonths() + " months";
        }
        if (duration.getWeeks() >= 1) {
            durationString += duration.getWeeks() + " weeks ";
        }
        if (duration.getDays() >= 1) {
            durationString += duration.getDays() + " days";
        }
        durationString += " since your last backup. Would you like to run one?";
        return durationString;
    }
    
    public String timeSinceLastBackupString() {
        return timeSinceLastBackupString(periodSinceLastBackup, backupEverRan);
    
    
    
    }
    

    DatabaseBackupController. This class, as it’s named, controls the whole process. From reminder, to executing the actual backup code.

    public class DatabaseBackupController
    /***********variables*************/
    String scheduleText; //Daily, Weekly, Monthy, or Never. It's set in our options panel.
    String timeText; //Time of day to run the backup, morning, day, or night. As 04:00-12:00 etc…
    Timestamp lastBackupRun; //Timestamp from DB (Herd is our abstracted class) from when it was last run.
    Timestamp lastBackupRunScheduleSetTime; //Timestamp from DB when the backup was set.
    Herd herd; //Herd is a custom datatype we use, it's basically a wrapper around a Derby table.
    
    /***********Method Headers**********/
    public DatabaseBackupController(Herd herd) //Constructor
    //Sets global variables, based on values in DB
    public void setupBackupReminder() 
    //calls DatabaseBackupReminder, passes global variables.
    public boolean checkBackupReminder()
    //Checks to make sure the current backup is valid within the duration since last backup
    public void runBackupPrompt() 
    //When we are in fact going to backup, calls BackupRunner instance.
    
    
    /**********full method code****************/
        public DatabaseBackupController(Herd herd) {
        this.herd = herd;
        scheduleText = herd.getBackupSchedule();
        timeText = herd.getBackupTime();
        lastBackupRun = herd.getBackupScheduledLastRun();
        lastBackupRunScheduleSetTime = herd.getBackupScheduledDatetime();
    }
    
    public void setupBackupReminder() {
        DatabaseBackupReminder dbReminder = new DatabaseBackupReminder(scheduleText, timeText, lastBackupRun, lastBackupRunScheduleSetTime, herd);
        Thread dbBackupThread = new Thread(dbReminder);
    
        dbBackupThread.start();
    }//end setupBackupReminder
    
    public boolean checkBackupReminder() {
        DatabaseBackupReminder dbReminder = new DatabaseBackupReminder(scheduleText, timeText, lastBackupRun, lastBackupRunScheduleSetTime, herd);
        return dbReminder.getBackupStillValid();
    }
    
    public void runBackupPrompt() {
        DatabaseBackupReminder dbReminder = new DatabaseBackupReminder(scheduleText, timeText, lastBackupRun, lastBackupRunScheduleSetTime, herd);
        int response = JOptionPane.showConfirmDialog(null, dbReminder.timeSinceLastBackupString());
        if (response == JOptionPane.YES_OPTION) {
            //NbPreferences.forModule(BackupSettingsPanel.class).putLong("databaseschedullastrun", Calendar.getInstance().getTimeInMillis());
            LoadStatusDialog lsd;
            lsd = null;
            lsd = new LoadStatusDialog(WindowManager.getDefault().getMainWindow(), false, true);
            lsd.setVisible(true);
            Thread br = new Thread(new BackupRunner(herd,lsd));
            br.start();
        }
    }
    }//end class
    

    Class DbBackupAction handles the local backup aspect. We backup locally, then send that file offsite in another class.
    This implements runnable, so it will handle the backup asynchronously and not cause the whole program to hang up.

    class DbBackupAction implements Runnable {
    
    private boolean backupSuccess;
    
    public DbBackupAction() {
        this.backupSuccess = false;
    }
    
    public void runBackup() {
    }
    
    @Override
    public void run() {
        Connection connection = JDBCUtils.getConnection();
        String dbName = NbPreferences.forModule(DatabasePanel.class).get("dbName", "");
        try {
            DerbyUtils.backUpDatabase(connection, dbName);
        } catch (SQLException ex) {
            Exceptions.printStackTrace(ex);
        }
        setBackupSuccess(true);
    }
    
    /**
     * @return the backupSuccess
     */
    public boolean isBackupSuccess() {
        return backupSuccess;
    }
    
    /**
     * @param backupSuccess the backupSuccess to set
     */
    public void setBackupSuccess(boolean backupSuccess) {
        this.backupSuccess = backupSuccess;
    }
    }
    

    BackupRunner handles both onsite/offsite backups. Uses DbBackupAction && RemoteBackupAction

    class BackupRunner implements Runnable {
    
    Herd herd;
    LoadStatusDialog lsd; 
    
    BackupRunner(Herd herd, LoadStatusDialog lsd) {
        this.herd = herd;
        this.lsd = lsd;
    }
    
    @Override
    public void run() {
    
    
    
        DbBackupAction dba = new DbBackupAction();
        Thread dbaThread = new Thread(dba);
    
        dbaThread.start();
        while (dbaThread.isAlive()) {
            try {
                dbaThread.join();
            } catch (InterruptedException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    
    
        if (dba.isBackupSuccess()) {
    
            RemoteBackupAction rba = new RemoteBackupAction();
            lsd.setProgressBarIndeterminate(true);
            Thread rbaThread = new Thread(rba);
            rbaThread.start();
            while (rbaThread.isAlive()) {
                try {
                    rbaThread.join();
                } catch (InterruptedException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
    
    
    
            if (rba.isBackupSuccess()) {
    
    
                herd.setBackupScheduledLastRun(new Timestamp(Calendar.getInstance().getTimeInMillis()));
                HerdService hs = new HerdDaoService();
                hs.update(herd);
    
                EventBus.publish(new RefreshStartScreenEvent());
            }
        }
    }
    }
    

    RemoteBackupAction handles FTPing out backup offsite.

    class RemoteBackupAction implements Runnable {
    
    Thread thread;
    LoadStatusDialog lsd;
    File backupFile;
    Pref pref;
    private boolean backupSuccess;
    
    public RemoteBackupAction() {
        backupSuccess = false;
    }
    
    public void runThread() {
    
                    backupSuccess = true;
    
                    try {
                        DerbyUtils.remoteBackupDatabase(backupFile);
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(null,
                                "This option is not available when working offline.");
                        System.out.println("SQLExcption: " + ex);
                        backupSuccess = false;
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null,
                                "Unable to connection to ftp site for remote backup.");
                        System.out.println("IOExcption: " + ex);
                        backupSuccess = false;
                    }
    
    
    
    }
    
    public void startOffsiteBackup() {
        pref = CentralLookup.getDefault().lookup(Pref.class);
        System.out.println("pref.isOnline(): " + pref.isOnline());
        if (!pref.isOnline()) {
            JOptionPane.showMessageDialog(null,
                    "This option is not available when working offline.");
            return;
        }
    
        File[] files = DerbyUtils.getListOfBackups();
        if ((files == null) || (files.length < 1)) {
            JOptionPane.showMessageDialog(null,
                    "There are no backup files available for upload. "
                    + "Please create a local backup.");
            return;
        }
        Backup[] backups = new Backup[files.length];
        if (files.length > 0) {
            Date[] dates = new Date[files.length];
            String[] herdCodes = new String[files.length];
            SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
            for (int i = 0; i < files.length; i++) {
                try {
                    String[] splitFileName = files[i].getName().split("_");
                    herdCodes[i] = splitFileName[0];
                    dates[i] = inFormat.parse(splitFileName[1].split("//.")[0]);
                    backups[i] = new Backup(herdCodes[i], files[i], files[i].getName(), dates[i]);
                } catch (ParseException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        } else {
            System.out.println("no backup files yet");
        }
    
        Arrays.sort(backups, Collections.reverseOrder());
    
        if (backups[0] != null) {
    
            this.backupFile = backups[0].getFile();
        } else {
            // Cancel button selected
            return;
        }
    
        runThread();
    }
    
    /**
     * @return the backupSuccess
     */
    public boolean isBackupSuccess() {
        return backupSuccess;
    }
    
    @Override
    public void run() {
        startOffsiteBackup();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i am using the MVVM design pattern and do not want much code in
I usually try to do TDD with not much analysis (no diagrams) before start
Writing my first C# application...never touched the language before and not much of a
Before I begin, I must warn you that I'm not much of a web
I have some existing code in C# that I'm trying to move to an
not much of a programming question, but development related still, I'm starting Android development
Not much to say about this question...
I'm not much into COM interfaces, so i have a small question, say I
This is driving me crazy and has resulted in lost work (not much, at
I know XHTML CSS but PHP knowledge is not much and i want to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.