Solved Prevent Task from being retriggered if already running

Discussion in 'Spigot Plugin Development' started by Kaxzer, Jul 17, 2021.

  1. Hi :),

    I wrote an anonymous BukkitRunnable (from the example of the wiki) and it works.
    But I would like to prevent the task from being retriggered if it is already running.

    I have an EventHandler for a BlockDamageEvent that launch a new Runnable using .runTaskTimer.
    The task is looping while the timer is not completed or the task not canceled.

    This works fine when I left-click once on a block (triggering BlockDamageEvent) and that I wait the job is complete (timer over).
    But if I left-click more than once on the same block, it triggers a new instance of the task and this override the timer of the first instance, messing the operation of the first task.

    Basically I want that for each player, only one instance of this task can run at once.

    Code (Java):
    public class BuildEvent implements Listener {
        private final JavaPlugin plugin;
        public BuildEvent(JavaPlugin plugin) {
            this.plugin = plugin;
        }
       // some function
       // variables init

        @EventHandler
        public void onDamageBlock (BlockDamageEvent eventBreak) {
            // variables init
            // do something
            new BukkitRunnable() {
                @Override
                public void run() {
                    // variables
                    if(condition){
                        // do something
                        cancel();
                    }
                    else if(timer >= time){
                        // do something
                        cancel();
                    }
                    timer += 5; // timer = period of the task
                }
            }.runTaskTimer(plugin, 0L, 5L); // 20ticks/s
        }
    }
    I do not understand well the scheduler programming.
    Can you please tell me the right way to solve this?
     
  2. 1 word: boolean
     
    • Agree Agree x 1
    • Winner Winner x 1
  3. Nvm, when I tried it I put the boolean inside the Runnable instead of the EventHandler, and I thinked it won't works elsewhere...
    Ty