Can't get runTaskLater working

Discussion in 'Plugin Development' started by Boscos, Apr 9, 2021.

Thread Status:
Not open for further replies.
  1. Offline

    Boscos

    Hello, I am relatively new to coding plugins and I am having an issue with defining plugin so that I can use runTaskLater
    This is in my Main class, called Main, and is my current attempt
    Code:
    private static Main instance;
    
        public static Main getPlugin(){
            return instance;
        }
    In my onEnable() I have this line:
    Code:
    instance = this;
    The task I am trying to run is reached with a method:
    Code:
    while (inGUI.get(uuid)) {
                        for (int i = 0; i < names.length; i++) {
                            int finalI = i;
                            Bukkit.getServer().getScheduler().runTaskLater(getPlugin(), () -> inv.setContents(contents.get(finalI)), ticks);
                        }
                    }
    When the command and code is run, basically the server just times out and I have to kill it.
    I have two suspicions on what might be wrong:
    [1] The plugin is not defined correctly (issue I was having earlier but I believe I fixed)
    [2] The for loop is running millions of times and timing out the server (I believe it has to be this)
    Is there a way to space out each run of the for loop if that is the case? I know I can't use sleep or wait as that will freeze the server.
    Thanks for any help, let me know if you need any more info to help.
     
  2. Offline

    KarimAKL

    @Boscos You never break out of the while loop, so it repeats infinitely and times out the server.
     
  3. Offline

    Chr0mosom3

    Instead of using a while loop, you could use a if statment, and a runTaskTimer().

    How it would look like in pseudo code:
    Code:
    if inGui {
    BukkitRunnable{
    inv.setContents(contents.get(finalI)), ticks
    }.runTaskTimer()
    
    A task timer just repeats the code every # of ticks, this is how a task timer would look like:
    Code:
    new BukkitRunnable() {
    @Override
    public void run() {
    inv.setContents(contents.get(finalI));
    if (!inGUI.get(uuid)) this.cancel();
    }
    }.runTaskTimer(arg0, arg1, arg2);
    
    arg0 is your plugin, or your main class
    arg1 is the delay, aka the number of ticks needed to wait until the loop runs for the first time
    arg2 is the ticks in between each run of the loop

    Inside the loop, you can cancel it by running this.cancel();
    wiki entry on this topic
     
    Boscos likes this.
  4. Offline

    Boscos

    Got everything fixed, thanks!
     
    Chr0mosom3 likes this.
Thread Status:
Not open for further replies.

Share This Page