如何每小时呼叫function? 另外,我该如何循环呢?

我需要一种简单的方法来每隔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(); } } } 

我需要运行一个我每小时都要实现的function,怎么样? 记住:该函数将使用l1和l2。 另外,我如何循环这个以获得中间的每个块?

创建一个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 ,则可以访问l1l2 。 要进行编译,您需要将它们标记为final

使用Timer对象的优点是它可以处理多个TimerTask对象,每个对象都有自己的计时,延迟等。只要你通过将它声明为类来保持Timer对象,你也可以启动和停止计时器。变量或其他东西。

我不知道如何让它们之间的每个块。

创建一个永远运行的线程,每小时唤醒一次以执行数据。

 Thread t = new Thread() { @Override public void run() { while(true) { try { Thread.sleep(1000*60*60); //your code here... } catch (InterruptedException ie) { } } } }; t.start(); 

您必须使用Bukkit Scheduler:

 public void Method(){ this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { // Your code goes here Method(); } }, time * 20L ); } 

您必须使用此方法创建方法,并且必须调用相同的方法。

  1. 最简单的方法(在我看来)是使用Thread (上面的评论提到了它)。
  2. 您还可以在javax.swing.Timer使用Timer
  3. 但我认为 – 正如101100所说 – 你可以使用TimerTask 。 您可以查看此链接 (来自IBM)