Solved Runnable

Discussion in 'Plugin Development' started by DoggyCode™, Mar 31, 2016.

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

    DoggyCode™

    I have a question, when making a class extending BukkitRunnable, it asks me to implement the run() method. I'm just wondering, when will the code inside the run method run? And can I make it a repeating task, or a delayed task?
     
  2. Offline

    ski23

    I've always wondered this as well. I've mainly used runnables in other classes and have rarely put them in their own classes. As an extension to this question, Is there a very good reason to often break up runnables into their own classes?
     
  3. Offline

    CoolDude53

    @DoggyCode™ You make classes that extend a runnable when it becomes more practical than creating an anonymous class every time you want to make a task. It can become more practical due to repetition, code readability, or functionality (through the use of constructors). The run method is called by a task, specifically a BukkitTask, and is executed based on the way you call it, whether that be immediately, delayed, repeated, and/or async. The way you call the runnable is handled outside of the runnable class.

    @ski23 The main reasons to break up runnables into their own classes, is for 1) to simplify repetition 2) a need to pass through variables through constructors 3) readability.
     
    WolfMage1 likes this.
  4. Offline

    WolfMage1

    Just take your class that extends BukkitRunnable
    Code:
    public class MyRunnable extends BukkitRunnable{
       
        @Override
        public void run(){
            //What you want to run.
        }
       
    }
    then just call it like the scheduler

    https://jd.bukkit.org/org/bukkit/scheduler/BukkitRunnable.html
    http://wiki.bukkit.org/Scheduler_Programming
     
  5. Offline

    DoggyCode™

  6. Offline

    ski23

    Cool! Thanks for the information.
     
  7. Offline

    DoggyCode™

    You would call the run method by getting the instance of the class and using .runTaskLater for example.

    Example:

    Code:
    public class Cooldown extends BukkitRunnable{
      
      JavaPlugin plugin;
    
      int timer;
    
      public Cooldown(JavaPlugin plugin, int timer){
        this.plugin = plugin;
        this.timer = timer;
        this.runTask(this.plugin);
      }
    
      public void run(){
        if(this.timer<=0){
          Bukkit.broadcastMessage(ChatColor.RED + "Timer is up");
          this.cancel();
        } else {
          Bukkit.broadcastMessage(ChatColor.RED + "Timer ain't up: " + this.timer--);
          this.timer--;
        }
      }
    }
     
Thread Status:
Not open for further replies.

Share This Page