Solved Question About Saving Files

Discussion in 'Spigot Plugin Development' started by Allogeneous, Jun 28, 2016.

Thread Status:
Not open for further replies.
  1. I have a file that stores certain player locations. However, when I was testing my plugin, I noticed that if someone were to exit the server without using the /stop command or just hits the x button on the console the onDisable() method is not called which is what I use to save my file, this makes sense, but I was wondering if there was a work around for this. I am considering running a repeating task that saves the file every x number of minutes or something so if the server crashes or someone just x's out not all the data from that server run is lost. I mainly just wanted to know if this is a good idea or if there is a better/alternate way to do this. Any help is appreciated, thank you!
     
  2. save all players location ondisable then
    for (Player p : Bukkit.getOnlinePlayers()) {
    //save players file here
    }
     
  3. Yes, having a repeating task every 5 minutes or so is best. To make it even better you can mark the file(s) dirty when changes are made that need to be saved. Then in the task only save dirty files. This way you arent needlessly writing to disk every 5 minutes.

    Code (Text):

    public class MyPlugin extends JavaPlugin {
        boolean isDirty = false;

        public void onEnable() {
           new AutoSave(this).runTaskTimer(this, 0, 6000);
        }

        public void savePlayerLocation(Player player) {
            getConfig().set(player.getUniqueId() + ".location", player.getLocation());
            isDirty = true;
        }
    }

    public class AutoSave extends BukkitRunnable {
        private MyPlugin plugin;

        public AutoSave(MyPlugin plugin) {
            this.plugin = plugin;
        }

        public void run() {
            if (!plugin.isDirty) {
                return;
            }
            plugin.saveConfig();
            plugin.isDirty = false;
        }
    }
     
    For a more in depth example you can look at my UserCache plugin that saves two custom config files https://bitbucket.org/BillyGalbreath/usercache/
     
    • Like Like x 1
  4. Thank you so much for the help! I will definitely be adding this into my plugin. I just wanted to make sure that adding something like this was the right choice :)
     
Thread Status:
Not open for further replies.