Java虽然每1秒运行一次

问题描述 投票:0回答:5

我有一段时间的功能。如果是真的我只想每1秒进行一次。我不能使用Thread.sleep(),因为我正在制作Minecraft插件,它将停止服务器上的所有进程。还有另外一种方法吗?

感谢您的回复。

java while-loop bukkit
5个回答
4
投票

您正在寻找的是Bukkit Scheduler。它已集成到默认插件API中,可用于解决您的任务,如下所示:

int taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
    @Override
    public void run() {
        // do stuff
    }
}, delay, repeat);

delay设置为0,重复设置为20(20个Ticks为1秒)。

使用以下命令停止:

Bukkit.getScheduler().cancelTask(taskID);

0
投票

您可以创建一个java.util.TimerTask,它可以在指定的时间延迟后安排您的任务。更多细节:https://www.geeksforgeeks.org/java-util-timertask-class-java/


0
投票

如果你在主要的Thread.sleep()中使用Thread,你将阻止main thread并且为了避免这种情况,你需要创建一个单独的线程传递给你需要在你的线程中处理任何你想要的值,一些片段代码用于澄清:

public static boolean ENABLE_THREAD = true;

public static void main(String args[]){
    InnerThread minecraftThread = (new ThreadStack()).new InnerThread();
    minecraftThread.run();
}


public class InnerThread implements Runnable{
    @Override
    public void run() {
        int counter=0;
        while(ENABLE_THREAD){
            try {
                //YOUR CODE
                System.out.println(counter);
                Thread.sleep(1000);
                counter++;
                if(counter>10){
                    ENABLE_THREAD = false;
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

-1
投票

你可以使用System.currentTimeMillis()

public static void main(String[] args) {

    //The while(true) is to keep the next while loop running, otherwise, in 
    //this example, the condition System.currentTimeMillis()-past>=1000 
    //won't be true
    //It can be changed according to the needs

    long past = System.currentTimeMillis();
    while(true)
    while(System.currentTimeMillis()-past>=1000) 
    {
        /*
         *DO what you need to do     
         */
        past = System.currentTimeMillis();
    }
}

-2
投票

这是我能想到的最简单的解决方案。请检查它是否适合您。

long start = new Date().getTime();

    while(new Date().getTime() - start < 1000L)
    {
    //Do Something every 1sec
    //you need to update the start value everytime
    start = new Date().getTime();
    }
© www.soinside.com 2019 - 2025. All rights reserved.