Advertisement
PerryPlaysMC

TimeDetectionTask

Sep 22nd, 2020
1,205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. public void onEnable() {
  2.   createRunnable().runTaskTimerAsynchronously(this,
  3.                 20-(Bukkit.getWorld("world").getTime() % 20), 20);
  4. }
  5.  
  6.  
  7. private BukkitRunnable createRunnable() {
  8.         long threshold = 18; //Incase a skip happens we have this.
  9.         long activateAt = 16000; //What Minecraft time to activate this at.
  10.  
  11.         return (new BukkitRunnable() {
  12.             long prevTime = -1; //Checking for time skips/sleeping
  13.             @Override
  14.             public void run() {
  15.                 if((Bukkit.getWorld("world").getTime() % 20) != 0) {//Check if it got out of sync (from a command or something)
  16.                     cancel();
  17.                     createRunnable().runTaskTimerAsynchronously(MainClassExtendsJavaPlugin.this,
  18.                             20-(Bukkit.getWorld("world").getTime() % 20), 20);//Reschedule the task
  19.                     return;
  20.                 }
  21.                 if(!(prevTime == -1 || Bukkit.getWorld("world").getTime() - prevTime >= threshold)//Check if time jumped(from sleeping or other)
  22.                         || (Bukkit.getWorld("world").getTime() == activateAt)) {//Check if the time is the activation time
  23.                     onActivate();
  24.                     prevTime = -1;//Reset the skip check time
  25.                     return;
  26.                 }
  27.                 prevTime = Bukkit.getWorld("world").getTime(); //Update the skipChecktime
  28.             }
  29.             /**
  30.             This is run whenever the worldtime is the same as ActivateAt time or when someone sleeps/time skips
  31.              */
  32.             private void onActivate() {
  33.                 //Code here
  34.                 System.out.println("Nighttime!");
  35.             }
  36.  
  37.         });
  38.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement