Skip to content
MateoF24 edited this page May 8, 2026 · 5 revisions

OnTime API

OnTime exposes a programmatic API that allows other mods to interact with the timer system. The API surface is identical across all loaders (Fabric, NeoForge, Forge 1.20.1). What differs is how you register your entrypoint, documented per-loader below.

The API package is com.mateof24.api. The mod ID is ontime.


OnTimeAPI

Obtain the singleton instance:

OnTimeAPI api = OnTimeAPI.getInstance();

Timer management

boolean created = api.createTimer(String name, int hours, int minutes, int seconds, boolean countUp);
boolean removed = api.removeTimer(String name);
boolean started = api.startTimer(String name);
boolean stopped = api.stopActiveTimer();   // resets and clears active
boolean paused  = api.pauseActiveTimer();  // sets running=false on the active timer

Time control

boolean ok = api.setTimerTime(String name, int hours, int minutes, int seconds);
boolean ok = api.addTimerTime(String name, int hours, int minutes, int seconds);

Behavior control

// Update the finish command of an existing timer
boolean ok = api.setTimerCommand(String name, String command);

// Set repeat mode (count = -1 for infinite)
boolean ok = api.setTimerRepeat(String name, boolean repeat, int count);

Querying

Optional<TimerInfo>     t      = api.getTimer(String name);
Optional<TimerInfo>     active = api.getActiveTimer();
Map<String, TimerInfo>  all    = api.getAllTimers();
boolean                 exists = api.hasTimer(String name);

Scoreboard

String objectiveName = api.getScoreboardObjectiveName(); // returns "ontime_active"

The objective is updated server-side once per displayed second (1 Hz). It carries the active timer's name as the score holder and its remaining seconds as the score value. Useful with /execute if score @s ontime_active matches ....


TimerInfo

TimerInfo is a read-only Java record with derived helpers:

Field/Method Type Description
name() String Timer name
currentTicks() long Current tick count (20 ticks = 1 second)
targetTicks() long Total duration in ticks
countUp() boolean true for count-up, false for countdown
running() boolean Whether the timer is actively ticking
silent() boolean Whether the timer suppresses the tick sound globally
command() String Finish command assigned to this timer
repeat() boolean Whether repeat mode is enabled
repeatCount() int Max repetitions (-1 for infinite)
repeatsDone() int Completed repetitions so far
getCurrentSeconds() long currentTicks / 20
getTargetSeconds() long targetTicks / 20
getFormattedTime() String "HH:MM:SS" if hours > 0, otherwise "MM:SS"
getPercentage() float 0–100; for count-up returns 100 - elapsed%

TimerInfo is a snapshot taken at the moment of the call/event. It does not auto-update.


Event callbacks

Subscribe to timer lifecycle events. Callbacks receive a TimerInfo snapshot and are invoked on the server thread.

api.registerOnStart(info  -> { /* timer became active */ });
api.registerOnFinish(info -> { /* timer reached zero / condition met */ });
api.registerOnPause(info  -> { /* timer was paused */ });
api.registerOnResume(info -> { /* timer was resumed */ });
api.registerOnTick(info   -> { /* once per second while running */ });

Listeners are stored in a CopyOnWriteArrayList and surfaced through a guarded try/catch — a misbehaving listener cannot break the tick loop.

onTick fires once per second (matching the client sync interval), not every game tick. If you need higher resolution, install your own ServerTickEvents listener and read api.getActiveTimer() directly.

Example

api.registerOnFinish(info ->
    LOGGER.info("Timer {} finished at {}", info.name(), info.getFormattedTime()));

External finish conditions

Register a Supplier<Boolean> evaluated every tick. When it returns true the active timer finishes immediately, executing its command normally.

api.registerFinishCondition("speedrun", () -> someExternalCondition());
api.unregisterFinishCondition("speedrun");

This is independent from the built-in score and expression conditions (/timer condition). All three can coexist — whichever triggers first ends the timer. Exceptions thrown by the supplier are swallowed and logged.


Custom HUD renderer

Replace the built-in timer overlay with your own renderer. Must be registered client-side.

Implement ITimerRenderer:

public class MyRenderer implements ITimerRenderer {
    @Override
    public void render(GuiGraphics graphics, float partialTick,
                       String formattedTime, float percentage,
                       int x, int y, float scale) {
        // your rendering logic
    }
}

Register it (client-side initialization):

TimerRendererRegistry.register(new MyRenderer());
TimerRendererRegistry.unregister(); // restore default

The renderer is invoked from the HUD callback once per frame with the result of OnTime's nanoTime-anchored prediction (formattedTime and percentage are already smoothed). x, y and scale are the resolved values for the configured position preset.

ITimerRenderer and TimerRendererRegistry are client-side classes. Do not reference them from server or common code.


Placeholder system

Register custom placeholders resolved when a timer's finish command executes:

api.registerTimerPlaceholder("mykey", timer -> timer.getName().toUpperCase());

This registers {mykey} as a valid placeholder in any timer command. The resolver receives a Timer (server-side mutable instance) and is called once at command execution time.

Built-in placeholders

Placeholder Value
{name} Timer name
{time} Formatted time string
{ticks} Current tick count
{target} Target tick count
{seconds} Current seconds
{mode} "count-up" or "countdown"

Note on Placeholder API (Fabric)

registerTimerPlaceholder only feeds the internal placeholder system used by timer finish commands. To also expose your custom keys to other mods through Placeholder API, register them through Placeholders.register yourself. See Fabric — PlaceholderAPI.


Permissions

Replace the default OP-level check with your own backend (e.g. LuckPerms):

api.setPermissionProvider((source, node, fallbackLevel) -> {
    // return true if `source` has permission for `node`
});

fallbackLevel is the OP level the default check would have used. See LuckPerms Integration for a complete example.


WebSocket control

The optional WebSocket feed (default port 25581, off until enabled) can also be controlled programmatically:

api.startWebSocket(25581);
api.stopWebSocket();
boolean running = api.isWebSocketRunning();

See WebSocket Integration for the wire format.


Entrypoint registration

Fabric

public class MyModOnTimeIntegration implements OnTimeEntrypoint {
    @Override
    public void onOntimeInitialize(OnTimeAPI api) {
        api.registerOnFinish(info -> System.out.println(info.name() + " done"));
        api.registerTimerPlaceholder("mykey", timer -> "value");
    }
}

fabric.mod.json:

"entrypoints": {
    "ontime": ["com.example.mymod.MyModOnTimeIntegration"]
}

NeoForge / Forge (1.20.1)

Send via Inter-Mod Communication during InterModEnqueueEvent:

InterModComms.sendTo("ontime", "register", () -> (OnTimeEntrypoint) api -> {
    api.registerOnFinish(info -> System.out.println(info.name() + " done"));
});

OnTime processes IMC during InterModProcessEvent and invokes your entrypoint with the API instance.


Dependency declaration

Fabric

"depends": {
    "ontime": ">=3.0.0"
}

NeoForge / Forge

[[dependencies.yourmodid]]
modId = "ontime"
type = "required"
versionRange = "[3.0.0,)"
ordering = "BEFORE"
side = "BOTH"

Threading model

  • All API mutators (createTimer, startTimer, etc.) must be called from the server thread. From an off-thread context (HTTP handler, WebSocket, etc.) wrap the call with MinecraftServer.execute(...).
  • Listeners registered with registerOnStart/Finish/Pause/Resume/Tick are invoked synchronously on the server thread.
  • registerFinishCondition suppliers are also invoked on the server thread, every server tick. Keep them cheap — no blocking I/O.
  • Client-side renderer callbacks are invoked on the render thread.

Clone this wiki locally