Skip to content

Delayed Events

jtljac edited this page Aug 24, 2023 · 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 DelayedEventsHandler. 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 IDelayedEvent Interface, this interface contains 3 functions that tell the delayed event class when to execute, whether to requeue to be checked and executed again, and what to execute.

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;
}

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

This method is used to check to see if the event should be requeued in the Delayed Events Handler Class to be called again, it is called every time the event is checked, whether it is executed or not. This has been done so the Delayed event can be cancelled early, even if it hasn't been executed yet

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.

An example use of this function can be found 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 any more, this method allows you to cancel the event in these conditions.

@Override
public boolean shouldRequeue(final boolean hasFinished) {
    if (!hasFinished && startingPos.distToCenterSqr(player.position()) > 1) {
        player.sendSystemMessage(Component.literal("Teleport cancelled"));
        return false;
    }
     return super.shouldRequeue(hasFinished);
}

Queuing delayed events

To queue a delayed event, you use the static method DelayedEventsHandler#addEvent, and pass in an instance of a delayed event.

DelayedEventsHandler.addEvent(new DelayedTeleportEvent(destination, 5));

To simplify things, Dat Modding API contains an abstract base class that implements IDelayedEvent and is mostly setup for a timed delayed event, only needing the execute method to be overridden. This can be extended for easily setting up a delayed event.

Example Delayed Event

Dat Modding API also comes with an example delayed event for teleporting: DelayedTeleportEvent, which is setup to teleport the player to a specified location after a specified amount of time, cancelling if they move further than a block or disconnect.