如何每小时调用功能?另外,我该如何循环这个?

2022-09-03 17:24:44

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


答案 1

创建一个对象,并为其提供一个执行要执行的代码的对象。TimerTimerTask

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);

如果在函数中声明,则可以访问 和 。要进行该编译,您需要将它们都标记为 .hourlyTaskonPlayerInteractl1l2final

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

我不知道如何让每个块都介于两者之间。


答案 2

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

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