我需要一种每 60 分钟调用一次函数的简单方法。我怎样才能做到这一点?我正在制作一个 MineCraft bukkit 插件,这就是我所拥有的:
package com.webs.playsoulcraft.plazmotech.java.MineRegen;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin{
public final Logger log = Logger.getLogger("Minecraft");
@Override
public void onEnable() {
this.log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
this.log.info("Plaz's Mine Regen is now enabled!");
this.log.info("Copyright 2012 Plazmotech Co. All rights reserved.");
this.log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
@Override
public void onDisable() {
this.log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
this.log.info("Plaz's Mine Regen is now disabled!");
this.log.info("Copyright 2012 Plazmotech Co. All rights reserved.");
this.log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
public void onPlayerInteract(PlayerInteractEvent event) {
final Action action = event.getAction();
if (action == Action.LEFT_CLICK_BLOCK) {
Location l1 = event.getClickedBlock().getLocation();
} else if (action == Action.RIGHT_CLICK_BLOCK) {
Location l2 = event.getClickedBlock().getLocation();
}
}
}
我需要运行一个我将每小时实现的函数,如何实现?请记住:该函数将使用 l1 和 l2。另外,我怎样才能循环它以获得中间的每个 block ?
最佳答案
创建一个 Timer
对象并给它一个 TimerTask
来执行您想要执行的代码。
Timer timer = new Timer ();
TimerTask hourlyTask = new TimerTask () {
@Override
public void run () {
// your code here...
}
};
// schedule the task to run starting now and then every hour...
timer.schedule (hourlyTask, 0l, 1000*60*60);
如果您在 onPlayerInteract
函数中声明了 hourlyTask
,那么您可以访问 l1
和 l2
。要进行编译,您需要将它们都标记为 final
。
使用 Timer
对象的优点是它可以处理多个 TimerTask
对象,每个对象都有自己的计时、延迟等。您还可以启动和停止只要您通过将 Timer
对象声明为类变量或其他东西来保留它,计时器就可以使用。
我不知道如何获取中间的每个 block 。
关于java - 如何每小时调用一次函数?另外,我怎样才能循环这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10748212/