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

时间:2012-05-25 03:43:45

标签: java timer scheduled-tasks

我需要一种简单的方法来每隔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。另外,我如何循环这个以获得中间的每个块?

4 个答案:

答案 0 :(得分:26)

创建一个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);

如果您在hourlyTask功能中声明onPlayerInteract,则可以访问l1l2。要进行编译,您需要将它们标记为final

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

我不知道如何让每一个街区之间。

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

您必须使用Bukkit Scheduler:

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

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

答案 3 :(得分:1)

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