Cooldowns
SporeAPI has two ways to track cooldowns: Cooldown for named cooldowns shared across your plugin, and CooldownMap for a cooldown that lives inside one class.
Cooldown
Cooldown lets you track a cooldown for anything with a UUID, not just players.
Cooldown.createCooldown("mine_ability", 10) // 10 second cooldown
Cooldown.addCooldown("mine_ability", player.uniqueId)
if (Cooldown.isOnCooldown("mine_ability", player.uniqueId)) {
player.sendMessage("Still on cooldown!")
}
There are also some shortcuts on CommandSender to keep your code cleaner:
if (sender.withCooldown("mine_ability", 10)) {
// runs your logic and starts the cooldown, only if not already on cooldown
}
Expired cooldowns aren't removed on their own. They don't do anything, they just sit in memory. Call Cooldown.cleanup() whenever you want to clear them out, for example from a repeating task. To end one player's cooldown early, use Cooldown.removeCooldown(id, uuid).
CooldownMap
If you only need a cooldown inside one class (anti-spam on a toggle, a pay command), CooldownMap is simpler. You give it a duration once, and its entries expire by themselves, so there is nothing to clean up.
private val payCooldown = CooldownMap<UUID>(15, TimeUnit.SECONDS)
if (payCooldown.isOnCooldown(player.uniqueId)) return
payCooldown.add(player.uniqueId)
The key can be any type, not just a UUID. For example, CooldownMap<String> works for names or IDs.
| Method | What it does |
|---|---|
isOnCooldown(key) | Returns true if the key is still on cooldown |
add(key) | Starts the cooldown for the key |
getRemaining(key) | Returns the time left in milliseconds, or 0 if it isn't on cooldown |
remove(key) | Ends the cooldown for one key early |
clear() | Ends every cooldown in the map |
Showing the remaining time to a player:
val remaining = payCooldown.getRemaining(player.uniqueId)
if (remaining > 0) {
player.sendMessage("Wait ${remaining / 1000 + 1} more seconds!")
return
}
payCooldown.add(player.uniqueId)
Good to know:
- Calling
addagain restarts the timer. If the key is already on cooldown, it gets a fresh full duration, so checkisOnCooldownfirst if you don't want that. - Checking doesn't start the cooldown.
isOnCooldownonly reads. You have to calladdyourself. - It is thread safe, so you can use it from async tasks and events.
- The duration is fixed per map. If different actions need different lengths, create one
CooldownMapper action.
Which one should I use?
- Use
CooldownMapwhen the cooldown is used in one class. It cleans up after itself. - Use
Cooldownwhen several classes need to share the same cooldown by name, or you want thewithCooldownshortcut onCommandSender.