What is the recommended way to make a timer in Bukkit?

Discussion in 'Plugin Development' started by iceypotatoguy, Mar 12, 2021.

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

    iceypotatoguy

    I have been looking up how to create a timer in Bukkit, but I see that some people use BukkitScheduler, BukkitTask, and BukkitRunnable. What am I supposed to use?
     
  2. Offline

    Kars

  3. Offline

    Strahan

    Personally, I like BukkitRunnable. Nice and easy and clean.
    Code:
    new BukkitRunnable() {
      int counter = 0;
    
      @Override
      public void run() {
        Bukkit.broadcastMessage("Yay spam!");
        counter++; if (counter == 4) this.cancel();
      }
    }.runTaskTimer(this, 0L, 20L);
     
    iceypotatoguy likes this.
  4. Offline

    davidclue

    A easy and simple way to have repeating tasks is by setting up an abstract class like this:
    Code:
    import org.bukkit.Bukkit;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public abstract class RepeatingTask implements Runnable {
    
        private int taskId;
    
        public RepeatingTask(JavaPlugin plugin, int arg1, int arg2) {
            taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, this, arg1, arg2);
        }
        public void cancel() {
            Bukkit.getScheduler().cancelTask(taskId);
        }
    }
    And then calling it in any other class you want to create a repeating timer in using this:
    Code:
    new RepeatingTask (plugin, 0, 20) { //first int for initial delay in ticks and second int for time between intervals in ticks
        @Override
        public void run() {
            //code to run every 20 ticks (1 second)
            cancel(); // you can use this internally or externally if you create an instance to cancel the task when your finished to reduce lag
        }
    };
     
    Last edited: Mar 18, 2021
Thread Status:
Not open for further replies.

Share This Page