Bukkit 有一个内置的调度系统,你可以阅读
调度程序编程
使用它而不是普通的 Java 计时器,相信我。从长远来看,它会让你的生活更轻松。
为了做你想做的事,你需要一个BukkitRunnable
类来给调度器。
这是一个通用的,我出于示例目的过度简化了:
public class Callback extends BukkitRunnable{
private Object targetObject;
public Method targetMethod;
private Object[] perameters;
public Callback(Object targetObject, String methodName, Object[] argsOrNull){
try {
this.targetMethod = targetObject.getClass().getMethod(methodName, (Class<?>[]) argsOrNull);
} catch (Exception e){
e.printStackTrace();
}
this.targetObject = targetObject;
this.perameters = argsOrNull;
}
public void run(){
try {
this.targetMethod.invoke(this.targetObject,perameters);
} catch (Exception e){
e.printStackTrace();
}
}
}
然后创建该可运行对象的对象,提供回调方法/道具作为参数,并将其提供给调度程序以在 60 秒内运行:
对于移动部分,您只需要在物品掉落且尚未有人移动时观察。
public class DropWatcher implements Listener {
private Boolean hasAnythingMoved;
private Boolean dropped;
private Pwncraft plugin;
private Player player;
public DropWatcher(Pwncraft plugin, Player player){
this.player = player;
this.hasAnythingMoved = false;
this.dropped = false;
this.plugin = plugin;
this.plugin.pluginManager.registerEvents(this, plugin);
}
//Drop event listener: When the player drops an item, it sets dropped to true, and initiates the countdown.
@EventHandler
public void onDropItem (PlayerDropItemEvent e) {
if(e.getPlayer().equals(this.player) && !this.dropped){
this.dropped = true;
BukkitCallbackTask doInSixtySeconds = new BukkitCallbackTask(this, "timesUp" , null);
doInSixtySeconds.runTaskLater(plugin, 1200); // time is in ticks (20 ticks +/- = 1 sec), so 1200 ticks = 1 min.
}
}
//Watches for other-players' movement, and sets hasAnythingMoved to true if so.
@EventHandler
public void onMove (PlayerMoveEvent e){
if(!e.getPlayer().equals(this.player) && this.dropped && !this.hasAnythingMoved){
this.hasAnythingMoved = true;
}
}
/*
This is the method the runnable calls when the timer is up.
It checks for movement, and if so, sends a message and explodes the player
(Just because it can. You're welcome to veto the explosion.)
*/
public void timesUp(){
if(this.hasAnythingMoved){
this.player.sendMessage("Someone moved! Time to party!");
this.player.getWorld().createExplosion(this.player.getLocation(), 5F);
this.dropped = false;
this.hasAnythingMoved = false;
}
}
}