RoomDefinition: onAlarm() hook

Available since @irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room host

The onAlarm() hook of a room definition runs when the room’s alarm is due, whether the room is active or hibernated then, and without a player connected. room.setAlarm() sets the alarm.

Syntax

defineRoom({
  onAlarm(room, info) {},
});

Parameters

room
The Room whose alarm is due.
info

An object with these properties:

scheduledAt
The time the alarm was set to, in wall-clock milliseconds. It’s in the past when the room couldn’t wake in time.
retry
0 for the first run, then counting the runs after onAlarm threw.

Return value

None, or a Promise. The alarm is cleared once onAlarm returns or its promise resolves, unless it set a new one.

Exceptions

If onAlarm throws, or its promise rejects, it runs again after 2, 4, 8, 16, 32 and 64 seconds (ALARM_RETRIES), with retry counting from 0, and then the alarm is dropped and the error logged. The room keeps running. An onAlarm that set a new alarm before throwing keeps the new one and isn’t retried, unless the new one is already due, which runs on the same schedule.

Description

A room has one alarm. It’s room state, so it survives hibernation and room host crashes. onAlarm runs at the alarm’s time by room.now(), never early. A hibernated room wakes for it, with onWake()’s reason set to "alarm", and runs onAlarm straight after onWake. When the room can’t wake in time, as when the project is out of credit, onAlarm runs at the next wake with scheduledAt in the past.

onAlarm runs at least once per alarm: a room host that crashes inside it runs it again. Make it safe to repeat. Setting the alarm again to the time it holds, once that time has come, doesn’t count as a new alarm, so onAlarm still clears it.

A room that wakes for its alarm with no one connected hibernates again as soon as onAlarm is done, and is billed at least 10 seconds for the wake. Alarm wakes are limited to 50 a second per project, so many rooms with an alarm at the same time run late; add a few minutes of jitter to such times.

Examples

A daily reset

A room with no ticks resets its daily quest at a time near midnight UTC, whether anyone is connected or not.

// daily.ts
import { defineRoom, defineSchema, entity } from "@irtio/room";

const Quest = entity("quest", { day: "u32", progress: "u32" });
const DAY = 24 * 3600_000;

function nextReset(now: number): number {
  return (Math.floor(now / DAY) + 1) * DAY + Math.floor(Math.random() * 5 * 60_000);
}

export default defineRoom({
  schema: defineSchema({ state: Quest }),
  onCreate(room) {
    room.setAlarm(nextReset(room.now()));
  },
  onAlarm(room) {
    room.state.day = Math.floor(room.now() / DAY);
    room.state.progress = 0;
    room.setAlarm(nextReset(room.now()));
  },
});

See also

Runtime availability

Hosted roomsirt dev@irtio/testingSelf-hosted room host
onAlarm()0.10.10.10.1