Home > OS >  Java asynchronously wait x seconds
Java asynchronously wait x seconds

Time:11-06

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.

CodePudding user response:

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
      Thread.sleep(1000)
      System.out.println("Time to wake up");
    }
  }

thread.start();
  • Related