Solved How Do I Cancel runTaskTimer() If There Is An Event Happened

Discussion in 'Spigot Plugin Development' started by ytredstone, Nov 30, 2020.

  1. So I want to cancel my task when an PlayerItemHeldEvent happens.

    I am doing simple gun reload and want to check: if a player changed his hotbar slot, then the reload task will be cancelled

    Here is the code (idk how it can help):
    Code (Java):
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
            //Player only command
            if(sender instanceof Player){
                Player p = (Player) sender;
                int timeLeft = cooldownManager.getCooldown(p.getUniqueId());
                //If the cooldown has expired
                if(timeLeft == 0){
                    //Use the feature
                    p.sendMessage(ChatColor.GREEN + "Feature used!");
                    //Start the countdown task
                    cooldownManager.setCooldown(p.getUniqueId(), CooldownManager.DEFAULT_COOLDOWN);
                    new BukkitRunnable() {
                        public void run() {
                            int timeLeft = cooldownManager.getCooldown(p.getUniqueId());
                            cooldownManager.setCooldown(p.getUniqueId(), --timeLeft);
                            p.sendTitle("", ChatColor.GREEN+"                   Перезарядка...");
                            if(timeLeft == 0){
                                p.getItemInHand().setDurability((short) 0);
                                p.sendTitle("", ChatColor.GREEN+"                   Перезаряжен!");
                    }.runTaskTimer(this.plugin, 20, 20);

                    //Hasn't expired yet, shows how many seconds left until it does
                    p.sendMessage(ChatColor.RED.toString() + timeLeft + " seconds before you can use this feature again.");
                sender.sendMessage("Player-only command");

            return true;
    And here is code (again, idk how it can help):
    Code (Java):
    public class CooldownManager {

        private final Map<UUID, Integer> cooldowns = new HashMap<>();

        public static final int DEFAULT_COOLDOWN = 10;

        public void setCooldown(UUID player, int time){
            if(time < 1) {
            } else {
                cooldowns.put(player, time);

        public int getCooldown(UUID player){
            return cooldowns.getOrDefault(player, 0);
  2. Store the BukkitRunnable that you create and use #cancel()
    • Like Like x 1
  3. Thank you so much!
    • Friendly Friendly x 1