Writing a repeating task for a plugin

We already have a BukkitRunnable class. Therefore, in order to run a task timer, we just need to determine the delay and the period by which the task is delayed. We want the delay to be 0. That way, if it is night when the plugin is enabled, the time will be set to noon right away. As for the period, we can repeat the task every second if we want to keep the sun always directly above. The task only contains one simple line of code. Repeating it often will not cause the server to lag. However, repeating the task every minute will still prevent the world from ever growing dark and will be less of a strain on the computer. Therefore, we will delay the task by 0 ticks and repeat it every 1,200 ticks. This results in the following line of code:

runnable.runTaskTimer(this, 0, 1200);

With this, we started a repeating task. It is good practice to cancel repeating tasks when the plugin is disabled. To accomplish this, we will store the BukkitTask as a class variable so that we can access it later to disable it. Once you have canceled the task within the onDisable method, the entire AlwaysDay plugin is given in the following code:

package com.codisimus.alwaysday;

import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

public class AlwaysDay extends JavaPlugin {
    BukkitTask dayLightTask;

    @Override
    public void onDisable() {

        dayLightTask.cancel();

    }

  @Override
  public void onEnable() {
    BukkitRunnable bRunnable = new BukkitRunnable() {
      @Override
      public void run() {
        for (World world : Bukkit.getWorlds()) {
          //Set the time to noon
          world.setTime(6000);
        }
      }
    };

    //Repeat task every 1200 ticks (1 minute)
    dayLightTask = bRunnable.runTaskTimer(this, 0, 1200);
  }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.246.254