我正在尝试制作一个类似锦标赛的插件,里面有一个start-game命令,可以在从10开始倒计时后开始比赛。然而,我找不到一种方法来等待1秒作为倒计时的间隔。我已经尝试过Object.wait(long)和BukkitScheduler.setRepeatingDelayedTask(),但它们都不适合我(object.wait()在我的编辑器中返回java.lang.IllegalMonitorStateException: current thread is not owner和BukkitScheduler.setRepeatingDelayedTask()错误)。有人知道解决这个问题的办法吗?
发布于 2021-10-17 20:34:54
使用BukkitScheduler是解决方案。但是,它以滴答为单位计入20 ticks = 1 seconds。
所以,你必须这样做:
private BukkitTask task;
private int count;
public void startTimer() {
count = 10; // restart count down at 10 seconds
task = Bukkit.getScheduler().runTaskTimer(MyPlugin.getInstance(), ()-> {
// here what you want
if(count == 0)
task.cancel(); // cancel the task if the counter is finished
count--; // reduce the counter
}, 20, 20);
}第一个"20“是启动调度程序之前的时间。第二个是每次调用之间的时间(都以节拍为单位)。
此外,不要使用Thread.sleep()或Object.wait(),因为它们可能会冻结整个服务器,并且可能会使所有服务器超时……
发布于 2021-10-20 19:45:29
// See how many seconds have been counted
private int count;
private BukkitTask task;
public void doStuff() {
// Reset count
count = 0;
task = new BukkitRunnable() {
@Override
public void run() {
// If count is less than or equal to ten, increment count, otherwise set count to -1.
count = count <= 10 ? count + 1 : -1;
if (count >= 10 || count == -1) {
// Cancel task if count is over 10s
task.cancel();
return;
}
Bukkit.getLogger().log(Level.INFO, "Seconds passed: " + count + "!";
}
}.runTaskTimer(YourPlugin.getPlugin(), 0, 20);
}https://stackoverflow.com/questions/69608306
复制相似问题