Search code examples
javaminecraftbukkit

Java asynchronously wait x seconds


To give some details about what I'm trying to do: I'm making a Minecraft plugin in Java. I have an Object which is bound to the Player object of Minecraft using a HashMap.

I have a method in this object which is something like:

    public void faint() {
        ... //Apply the effect on the player

        //wait for x seconds, and if the player didn't already wake up, wake them up. (player.wakeUp())
    }

Obviously, there will be a lot of stuff going on, so I want this to happen asynchronously. The timer will go on in the background and it won't block anything else in the code.

Sorry if my question is too simple, but I really checked the web and I'm new to Java, so forgive my ignorance.


Solution

  • Use the Bukkit scheduler.

    Bukkit.getScheduler().runTaskLater(yourPluginInstance, () -> {
        // put code here to run after the delay
    }, delayInTicks);
    

    When the code runs after the delay it will run on the main server thread.