Bukkit Runnables - JustKato/BukkitWiki GitHub Wiki
Running code after X amount of ticks
The bukkit runnable is amazing for waiting for a while before running some code, this works great in many cases, especially cooldowns on items!
// Somewhere where you can access it if needed it.
// You can also write BukkitRunnable runnable = new Bukk...
BukkitRunnable runnable;
// In the code
runnable = new BukkitRunnable() {
@Override
public void run() {
// Run your code here;
}
};
runnable.runTaskLater(plugin, 20*15); // The code will run 15 seconds later, as the time is in ticks.
Running code every X amount of ticks
BukkitRunnable loop = new BukkitRunnable() {
@Override
public void run() {
Bukkit.broadcastMessage("The loop ran"); // This will broadcast every 5 seconds
}
};
loop.runTaskTimer(plugin, 0L, 20*5); // This will run every 5 seconds
Running code every X amount of ticks and canceling it after X amount of time
Right here I am using a timer basically, after X amount of times I cancel the whole runnable. If you want to you can use outside REFERENCES, for example if you are trying to play an animation over an entity you can check if the entity is still alive with:
Entity player = (Player) event.getEntity();
// inside the runnable
if ( player.isDead() ) this.cancel();
BukkitTask loop = new BukkitRunnable() {
int counter = 0; // Initialize a counter outside the main run() function
@Override
public void run() {
if ( counter >= 5) { // Check if the counter reached 5
this.cancel(); // Cancel this BukkitRunnable
} else { // We didn't reach the counter limit
counter++; // Add to the counter
Bukkit.broadcastMessage("The loop ran"); // This will broadcast every 5 seconds // Send the message
}
}
};
loop.runTaskTimer(plugin, 0L, 20); // This will run every 1 second