最近我开始开发一个Bukkit插件,我需要帮助我在代码中休眠/等待。我是java的新手,所以如果你能解释一下,我会很感激。这是我的代码:
@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);
}
}
答案 0 :(得分:2)
虽然通常你会使用Thread.sleep
这样的东西,这会冻结整个服务器,并且在那段时间内不会处理事件(所以即使玩家停止偷偷摸摸他们,他们' d仍然是从服务器看到的东西偷偷摸摸的。)
您需要做的是使用BukkitRunnable
(或者常规Runnable
和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);
}
答案 1 :(得分:0)
我知道这是一个老问题,但我想添加一些内容,以便寻找方法的用户可以找到这个。
最简单的说法是创建一个计划任务:
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
// The stuff which should be accomplished after the timer runs out goes here.
// Example:
player.sendMessage("The time has ran out!");
}, time);
现在,让我们了解一下这里发生了什么。基本上,se已创建延迟任务(有两种类型的计划任务:延迟和重复任务)。
上述方法的第一个参数是this
。这应该是您的主类的实例(org.bukkit.plugin.java.JavaPlugin的子类)。这意味着如果计划任务不在您的主类中,您将需要将this
替换为它的实例。第二个参数是new Runnable() { ... }
,我们实际上是在创建runnable。无论在计时器用完时应该执行什么,都应该进入花括号内。最后,最后一个参数:这是实际延迟,以TICKS
为单位。这意味着,如果您希望等待x秒,则必须乘以x * 20,因为刻度等于1/20秒,因此5秒将等于100个刻度。
如果您知道如何使用lambdas,则可以替换匿名类:
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, () -> player.sendMessage("The time has ran out!"), time);