Player data not writing to database when server restarts

Discussion in 'Spigot Plugin Development' started by ktri, Aug 9, 2018.

  1. Basically if a player does something on the server and then the server restarts before they logout their data will not be saved to the database. If, however, they logout and then the server restarts, their data is fine. I checked the console and it looks like when I press the restart button, it just kicks the players without saving their data (since my code logs to the console whenever data is written to the database when a player logs out). Is there a way to kick the players before the server shuts down? I tried this but it dosen't seem to work:

    in onEnable:

    Code (Text):
    try {
                Runtime.getRuntime().addShutdownHook(new ShutdownHandler());
            } catch(Exception e) {
                e.printStackTrace();
            }
    in ShutdownHandler:

    Code (Text):
    public class ShutdownHandler extends Thread{
       
        @Override
        public void run() {
            for(Player player: Bukkit.getServer().getOnlinePlayers()) {
                player.kickPlayer("Server restarting");
            }
        }
    }
    when I restart the server I get kicked with the message "Server closed" instead of "Server Restarting." The console also does not display the player's data being written to the database.
     
  2. Have you tried using the onDisable method?
     
    • Agree Agree x 2
  3. if you add a shutdown hook, it will (attempt to) be executed when the process's runtime has actually ended, not just when you use /stop or whatever. Following that logic, when you call /stop it will disable plugins, bukkit will kick everyone from the server, save the world, etc. etc, finish the bukkit process runtime and **THEN** call your shutdown hook, which is also unsafely accessing the now completely empty and shutdown bukkit api from another thread.

    BASICALLY, just save all your player data in the overridable JavaPlugin#onDisable method in your main class and you'll be fine.
     
    • Agree Agree x 1
  4. Saving data right at the event/command is more reliable if you don't want to lose data. A single UPDATE or INSERT INTO or REPLACE INTO here and there (in an async task) doesn't do any harm.

    If it's some event that fires very often (eg block or move events) you might want to buffer the saving into batches
     
  5. Thanks for all the info. I'll give onDisable a try.