Advertisement
KingFaris10

Bukkit - RepeatableRunnable class

Aug 27th, 2013
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. import org.bukkit.Bukkit;
  2. import org.bukkit.plugin.Plugin;
  3. import org.bukkit.scheduler.BukkitRunnable;
  4. import org.bukkit.scheduler.BukkitScheduler;
  5.  
  6. /**
  7.  * This class is provided as an easy way to handle repeating scheduled tasks. Do not use scheduleSyncRepeatingTask as when a new instance of this class is created, it automatically schedules one. Just create a new intstance.
  8.  * @author KingFaris10
  9.  */
  10. public abstract class RepeatableRunnable extends BukkitRunnable {
  11.  
  12.     private int repeatableTaskID = 0;
  13.     private long repeats = 0;
  14.     private long maxRepeats = 0;
  15.  
  16.     /**
  17.      * Create a new Repeatable Runnable that runs until the maximum amount of repeats. This will automatically schedule a repeating task.
  18.      *
  19.      * @param scheduler - The Scheduler of the server.
  20.      * @param yourPlugin - Your plugin object.
  21.      * @param delay - Delay in server ticks before executing first repeat.
  22.      * @param period - Period in server ticks of the task.
  23.      * @param amountOfTimes - The amount of times to call the onRun method.
  24.      */
  25.     public RepeatableRunnable(BukkitScheduler scheduler, Plugin yourPlugin, long delay, long period, long amountOfTimes) {
  26.         this.repeatableTaskID = scheduler.scheduleSyncRepeatingTask(yourPlugin, this, delay, period);
  27.         this.maxRepeats = amountOfTimes > 0 ? amountOfTimes : 1;
  28.     }
  29.  
  30.     @Override
  31.     public void run() {
  32.         if (this.repeats < this.maxRepeats) {
  33.             this.repeats++;
  34.             this.onRun();
  35.         } else {
  36.             try {
  37.                 if (Bukkit.getScheduler().isCurrentlyRunning(this.repeatableTaskID) || Bukkit.getScheduler().isQueued(this.repeatableTaskID)) Bukkit.getScheduler().cancelTask(this.repeatableTaskID);
  38.             } catch (Exception ex) {
  39.                 try {
  40.                     this.cancel();
  41.                 } catch (Exception ex2) {
  42.                 }
  43.             }
  44.         }
  45.     }
  46.  
  47.     public abstract void onRun();
  48.  
  49.     public long getRepeats() {
  50.         return this.repeats;
  51.     }
  52.  
  53.     public long getMaxRepeats() {
  54.         return this.maxRepeats;
  55.     }
  56.  
  57.     public void setTaskID(int taskID) {
  58.         this.repeatableTaskID = taskID;
  59.     }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement