Skip to content

Commit 1c3afbd

Browse files
committed
Implement scheduling APIs
1 parent fa62c21 commit 1c3afbd

File tree

2 files changed

+48
-4
lines changed

2 files changed

+48
-4
lines changed

packages/actor-core/src/actor/instance.ts

+25-1
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ export class ActorInstance<S, CP, CS, V> {
213213
timestamp: number,
214214
fn: string,
215215
args: unknown[],
216-
): Promise<void> {
216+
): Promise<string> {
217217
// Build event
218218
const eventId = crypto.randomUUID();
219219
const newEvent: PersistedScheduleEvents = {
@@ -244,6 +244,30 @@ export class ActorInstance<S, CP, CS, V> {
244244
this.actorContext.log.info("setting alarm", { timestamp });
245245
await this.#actorDriver.setAlarm(this, newEvent.t);
246246
}
247+
return eventId;
248+
}
249+
250+
async getEvent(eventId: string) {
251+
return this.#persist.e.find((x) => x.e === eventId);
252+
}
253+
254+
async cancelEvent(eventId: string) {
255+
const index = this.#persist.e.findIndex((x) => x.e === eventId);
256+
if (index !== -1) {
257+
if (index === 0 && this.#persist.e.length === 1) {
258+
this.actorContext.log.info("clearing alarm");
259+
await this.#actorDriver.deleteAlarm(this);
260+
} else if (index === 0) {
261+
this.actorContext.log.info("setting next alarm", { timestamp: this.#persist.e[1].t });
262+
await this.#actorDriver.setAlarm(this, this.#persist.e[1].t);
263+
}
264+
this.#persist.e.splice(index, 1);
265+
this.actorContext.log.info("cancelled event", { eventId });
266+
}
267+
}
268+
269+
async listEvents() {
270+
return this.#persist.e;
247271
}
248272

249273
async onAlarm() {
+23-3
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,37 @@
11
import type { AnyActorInstance } from "./instance";
22

3+
export interface ScheduledEvent {
4+
id: string;
5+
createdAt: number;
6+
triggersAt: number;
7+
fn: string;
8+
args: unknown[];
9+
}
10+
311
export class Schedule {
412
#actor: AnyActorInstance;
513

614
constructor(actor: AnyActorInstance) {
715
this.#actor = actor;
816
}
917

10-
async after(duration: number, fn: string, ...args: unknown[]) {
11-
await this.#actor.scheduleEvent(Date.now() + duration, fn, args);
18+
async after(duration: number, fn: string, ...args: unknown[]): Promise<string> {
19+
return await this.#actor.scheduleEvent(Date.now() + duration, fn, args);
1220
}
1321

1422
async at(timestamp: number, fn: string, ...args: unknown[]) {
15-
await this.#actor.scheduleEvent(timestamp, fn, args);
23+
return await this.#actor.scheduleEvent(timestamp, fn, args);
24+
}
25+
26+
async get(alarmId: string) {
27+
return this.#actor.getEvent(alarmId);
28+
}
29+
30+
async cancel(eventId: string) {
31+
await this.#actor.cancelEvent(eventId);
32+
}
33+
34+
async list() {
35+
return await this.#actor.listEvents();
1636
}
1737
}

0 commit comments

Comments
 (0)