MucaP MucaP - 9 days ago 5
Java Question

bukkit - Waiting?

Recently I started developing a Bukkit Plugin and I need help with sleeping/waiting in my code. I'm kinda new to java so if you could explain it, I would appreciate. Here is my code:

@EventHandler
public void onTnt(PlayerInteractEntityEvent e) {
Player clicker = e.getPlayer();
Player rightclick = (Player) e.getRightClicked();
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_PURPLE + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_RED + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
/* Then wait 3 sec. I've tried Thread.Sleep, wait() and sleep(), no sucess*/

if (!(rightclick.isSneaking())) {
rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "Bye bye.");
rightclick.setHealth(0);

}

}

Answer

While normally you'd use Thread.sleep for something like this, that would freeze the entire server, and events wouldn't be processed in that time (so even if the player stopped sneaking on their side, they'd still be sneaking from what the server sees).

What you need to do is use a BukkitRunnable (or alternatively a regular Runnable and getServer().getScheduler().scheduleSyncDelayedTask):

@EventHandler
public void onTnt(PlayerInteractEntityEvent e) {
    Player clicker = e.getPlayer();
    // Needs to be final to reference it later
    final Player rightclick = (Player) e.getRightClicked();
    rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_PURPLE + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
    rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_RED + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");
    rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!");


    BukkitRunnable task = new BukkitRunnable() {
        @Override
        public void run() {
            if (!(rightclick.isSneaking()))  {
                rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "Bye bye.");
                rightclick.setHealth(0);
            }
        }
    };
    // Run the task on this plugin in 3 seconds (60 ticks)
    task.runTaskLater(this, 20 * 3);
}
Comments