dev-mirzabicer
dev-mirzabicer

Reputation: 41

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.

Upvotes: 0

Views: 985

Answers (2)

Arthur Klezovich
Arthur Klezovich

Reputation: 2819

You can create a separate thread by implementing a Runnable interface like this and do the delay in there.

// This is happening in the main thread
Thread thread = new Thread(){
    public void run(){
      // This code will run async after you execute
      // thead.start() below
      try {
        Thread.sleep(1000);
        System.out.println("Time to wake up");
      } catch (InterruptedException e) {
        // See https://www.javaspecialists.eu/archive/Issue056-Shutting-down-Threads-Cleanly.html
        Thread.currentThread().interrupt();
      }
    }
  }

thread.start();

Upvotes: 0

Donut
Donut

Reputation: 405

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.

Upvotes: 0

Related Questions