How to cancel a task?!

Discussion in 'Spigot Plugin Development' started by wessel_f, Jun 2, 2015.

  1. Why will this not work:


    Code (Text):
    public static boolean runcountdown(){
            mode = 1;
            if (Bukkit.getOnlinePlayers().size() > 0){
                if (hasTimerStarted == 0){
                hasTimerStarted = 1;
                taskID2 = Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() { public void run() {
                    if (sec != -1){
                    if (sec != 0) {
                        for (Player p : Bukkit.getOnlinePlayers()){
                                p.setLevel(sec);
                                sec--;
                                Scoreboard.updateScoreboard();
                                }
                }else{
                    Bukkit.broadcastMessage("2");
                        for (Player p : Bukkit.getOnlinePlayers()){
                                p.setLevel(sec);
                                sec--;
                                Scoreboard.updateScoreboard();
                        }
                        rungame();
                        Bukkit.broadcastMessage(Main.prefix + "Game has been started!");
                        hasGameStarted = 1;
                        Bukkit.getServer().getScheduler().cancelTask(taskID2);
                }
                    }
                }}, 20, 20);
                }
            }
            if(Bukkit.getOnlinePlayers().size() < 1){
                Bukkit.broadcastMessage(Main.prefix + "Wait for more players (Min 2 players)");
            }
            return true;
        }
     
  2. The scheduler has a cancel method which takes a task id.
     
  3. For tasks that need to self-cancel, it's much easier to use a BukkitRunnable:
    PHP:
    new BukkitRunnable() {
        @Override
        public void run () {
            // Do your tasks here

            // When ready to cancel, call:
            this.cancel();
        }
    }.runTaskTimer(plugin, 20L, 20L);
     
    • Agree Agree x 2
  4. This shouldn't be used, like the schedule* methods.

    Use runTaskTimer, runTaskLater instead, it returns a BukkitRunnable instead of a taskId. Then use BukkitRunnable#cancel().


    Also:
    Don't use that many ints!
    Code (Text):
    mode = 1;
    that's totally not understandable, use enums!
    Code (Text):
    hasTimerStarted = 1;
    hasGameStarted = 0;
     
    Use booleans instead.
     
  5. To be fair, C doesn't have booleans. Maybe he's a professional C coder ;P
     
    #5 SubSide, Jun 2, 2015
    Last edited: Jun 2, 2015
  6. Code (C):
    #define false 0
    #define true 1
    now it does ;).
     
    • Funny Funny x 2