Skip to content

Delayed Events

jtljac edited this page Feb 10, 2020 · 8 revisions

Dat Modding API adds an easy method to delay code from executing till a defined condition is met, usually a set amount of time passing.

This is achieved using the class Delay Handler. This class contains the logic for processing delayed events, and provides methods for creating delayed events.

Creating a delayed event

To create a delayed event, you must create a class that implements the https://jtljac.github.io/DatModdingAPI/com/demmodders/datmoddingapi/interfaces/IDelayedEventInterface.html, this interface contains 3 events that tell the delayed event class when to execute, whether to requeue to be checked and executed again, and how to execute.

canExecute

This method checks to see if the delayed event should execute, it should return a boolean that is true if it should execute. An example of this would be in a timed event, when this method is called it would compare the expected execution time to the current time and return true if the current time is greater.

@Override
public boolean canExecute() {
    return System.currentTimeMillis() >= exeTime;
}

execute

This method is the actual code that is run when the delayed event is ready to execute, not much more to say than that

shouldRequeue

This method is used to check to see if the event should be requeued in the Delayed Event Class to be called again, it is called every time the event is checked, after canExecute and, if it could execute, execute. It is given a boolean that is true if the execute method was called, and is expected to return a boolean that is true if it should be requeued. This is usually used to requeue the event when canExecute returns false, however, the reason it has been implemented like this is so you can cancel the event from executing if some other conditions have been met. For example, in an event that teleports the player after a delay, if the player has moved or even logged out, you don't want to teleport them anymore, this method allows you to cancel the event in these conditions.

@Override
public boolean canExecute(){
    // Ensure the player is still on the server, and hasn't moved more than a block away from their start point
    if (player.isDead || player.hasDisconnected() || Math.abs(Math.pow(player.posX - startX, 2) + Math.pow(player.posZ - startZ, 2)) > 1){
        cancelled = true;
        if(!player.hasDisconnected()) player.sendMessage(new TextComponentString(textCancelledColour + "Teleport Cancelled"));
    }
    return super.canExecute() && !cancelled;
}
Clone this wiki locally