Event handlers and threads/runnables?

Discussion in 'Plugin Development' started by nonperson32835, Jun 30, 2016.

Thread Status:
Not open for further replies.
  1. Offline

    nonperson32835

    So I have the following code:
    Code:
       
    public void messagePlayerAfterDelay(Player player) {
            try {
                Thread.sleep(3000); //Sleep for 3 seconds
                player.sendMessage("You got damaged 3 seconds ago"); //Message player after 3 seconds
            } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
       
        @EventHandler
        public void playerHitPlayerEvent(EntityDamageByEntityEvent e) {
            Entity damaged = e.getEntity();
            if(damaged instanceof Player) {
                Player player = (Player) damaged;
                player.sendMessage("You just got damaged! ");
                messagePlayerAfterDelay(player);
            }
        }
    
    Basically, in the code above, I want the player to be messaged 3 seconds after they take damage. The problem is, that when calling
    Code:
    messagePlayerAfterDelay(player)
    , which has a 3 second delay, it causes a 3 second delay between when the player takes damage and when they take knockback (which occurs after the event handler is finished). For example, with that code, if a player were to get hit by another player, then they would stand still for 3 seconds and then take the damage from the hit as well as the knockback after 3 seconds has passed.

    I need the function messagePlayerAfterDelay to be ran without waiting for it to finish. I believe i need to use runnables / threads for this, but I was confused on how to do that because an event handler is involved. Basically, I want the player to be knocked back and take damage like normal, and then 3 seconds later get messaged.
     
  2. @nonperson32835 Bukkit rule 7: NEVER SLEEP THE THREAD! This will freeze the whole server as you are sleeping the main thread.

    Look into Bukkit schedulers, there is a nice wiki tutorial
     
  3. Offline

    Zombie_Striker

Thread Status:
Not open for further replies.

Share This Page