Scheduler API reference
Current emitted signatures and options for @db3.ai/app/scheduler.
On this page
Source-backed MarkdownImports and examples
Import supported APIs from @db3.ai/app/scheduler. These signatures come from the staged package used by consumers. Relative filenames in declarations describe type dependencies; they are not extra supported deep imports.
Use the guide for setup, executable examples, failure handling and ownership. A signature is not proof that every deployment or provider has been exercised.
Registration and due evaluation
ts
import { type Database } from '../db/index.js';
import { type Queue } from '../queue/index.js';
import type * as scheduler from './contracts/index.js';
import { ScheduledCall } from './ScheduledCall.js';
import { ScheduledJob } from './ScheduledJob.js';
/**
* Registers daily tasks, atomically claims due occurrences, and dispatches work.
*/
export declare class Scheduler {
#private;
private readonly database;
private readonly queue;
/**
* Creates a scheduler and attaches durable queue lifecycle recording.
*
* @param database - Application database containing occurrence history.
* @param queue - Queue used to dispatch scheduled jobs.
*/
constructor(database: Database, queue: Queue);
/**
* Registers a QueueableJob class or fresh-job factory.
*
* @param source - Zero-argument job class or parameterised factory.
* @returns Fluent scheduled job definition.
*/
job(source: scheduler.ScheduledJobSource): ScheduledJob;
/**
* Registers a short inline callback.
*
* @param callback - Callback executed directly by the scheduler worker.
* @returns Fluent scheduled call definition.
*/
call(callback: scheduler.ScheduledCallHandler): ScheduledCall;
/**
* Returns validated normalized definitions in registration order.
*
* @returns Registered scheduler definitions.
*/
definitions(): scheduler.ScheduledTaskDefinition[];
/**
* Evaluates and handles every task due for one canonical UTC minute.
*
* Due tasks run sequentially in registration order. Immediate failures are
* recorded and aggregated so one task cannot prevent later tasks from being
* considered.
*
* @param now - Instant whose UTC minute should be evaluated.
* @returns Structured evaluation summary.
*/
runDue(now?: Date): Promise<scheduler.SchedulerRunResult>;
/**
* Detaches queue lifecycle recording owned by this scheduler instance.
*/
close(): void;
/**
* Creates and dispatches one job with occurrence origin metadata.
*
* @param event - Claimed scheduled job definition.
* @param occurrence - Durable occurrence receiving queue events.
*/
private dispatchJob;
/**
* Runs one short inline callback and records its terminal state.
*
* @param event - Claimed scheduled callback.
* @param occurrence - Durable occurrence to update.
*/
private runCall;
/**
* Records an immediate dispatch, factory, or inline callback failure.
*
* @param occurrence - Claimed occurrence that failed.
* @param error - Immediate scheduler error.
*/
private failOccurrence;
}
Daily event configuration
ts
import type * as scheduler from './contracts/index.js';
/**
* Shared fluent timing configuration for scheduled jobs and calls.
*/
export declare abstract class ScheduledEvent {
abstract readonly kind: scheduler.ScheduledTaskKind;
protected configuredName: string | null;
protected configuredFrequency: scheduler.DailyScheduleFrequency | null;
protected configuredTimezone: string;
/**
* Sets the stable identity used for deduplication and history.
*
* @param name - Stable non-empty schedule name.
* @returns This scheduled event.
*/
name(name: string): this;
/**
* Schedules this task every day at local midnight.
*
* @returns This scheduled event.
*/
daily(): this;
/**
* Schedules this task every day at one local wall-clock time.
*
* @param time - Time in 24-hour HH:mm form.
* @returns This scheduled event.
*/
dailyAt(time: string): this;
/**
* Sets the IANA timezone used to interpret this event's local time.
*
* @param timezone - IANA timezone such as Europe/London.
* @returns This scheduled event.
*/
timezone(timezone: string): this;
/**
* Returns whether this event is due at one canonical UTC minute.
*
* @param instant - UTC minute being evaluated.
* @returns True when the configured daily time matches.
*/
isDue(instant: Date): boolean;
/**
* Returns the normalized public schedule definition.
*
* @returns Validated schedule definition.
*/
definition(): scheduler.ScheduledTaskDefinition;
/**
* Resolves the stable event name or throws when one is unavailable.
*
* @returns Stable event name.
*/
protected resolvedName(): string;
/**
* Returns the daily frequency or throws when none was configured.
*
* @returns Configured daily frequency.
*/
private frequency;
/**
* Returns the default stable name supplied by the concrete event type.
*
* @returns Default name, or null when explicit naming is required.
*/
protected abstract defaultName(): string | null;
/**
* Returns the known queue job name for public schedule inspection.
*
* @returns Queue job name, or null for calls and deferred factories.
*/
protected resolvedJobName(): string | null;
}
Scheduled job
ts
import { type QueueableJob } from '../queue/index.js';
import type * as scheduler from './contracts/index.js';
import { ScheduledEvent } from './ScheduledEvent.js';
/**
* Fluent daily schedule that creates a fresh QueueableJob when due.
*/
export declare class ScheduledJob extends ScheduledEvent {
private readonly source;
readonly kind: "job";
/**
* Creates a scheduled job definition.
*
* @param source - Zero-argument QueueableJob class or fresh-job factory.
*/
constructor(source: scheduler.ScheduledJobSource);
/**
* Creates the QueueableJob for one claimed occurrence.
*
* @returns Fresh serializable queue job.
*/
createJob(): QueueableJob;
/**
* Returns the class job name when no factory invocation is required.
*
* @returns Durable queue job name, or null for factories.
*/
resolvedJobName(): string | null;
/**
* Uses the durable class job name as the default schedule identity.
*
* @returns Default job name, or null for parameterised factories.
*/
protected defaultName(): string | null;
}
Inline call
ts
import type * as scheduler from './contracts/index.js';
import { ScheduledEvent } from './ScheduledEvent.js';
/**
* Fluent daily schedule for one short inline callback.
*/
export declare class ScheduledCall extends ScheduledEvent {
private readonly callback;
readonly kind: "call";
/**
* Creates a scheduled inline callback.
*
* @param callback - Short synchronous or asynchronous task.
*/
constructor(callback: scheduler.ScheduledCallHandler);
/**
* Runs the scheduled callback and awaits asynchronous completion.
*/
run(): Promise<void>;
/**
* Requires every callback schedule to declare a stable explicit name.
*
* @returns Null because anonymous callback identity is not durable.
*/
protected defaultName(): string | null;
}
Durable occurrence
ts
import { ActiveRecord, type FieldBuilder } from '../db/index.js';
import type * as scheduler from './contracts/index.js';
/**
* Values required to atomically claim one due scheduled occurrence.
*/
interface ScheduledOccurrenceClaim {
/** Stable registered schedule name. */
name: string;
/** Scheduled task kind. */
kind: scheduler.ScheduledTaskKind;
/** Canonical UTC minute represented by the occurrence. */
scheduledFor: Date;
/** Queue job name when known before a factory is invoked. */
jobName?: string;
}
/**
* Durable claim, execution state, and queue correlation for one scheduled task.
*/
export declare class ScheduledOccurrence extends ActiveRecord {
static table: string;
static primaryKey: string;
static labelFields: string[];
static comment: string;
/**
* Defines scheduler claim, queue correlation, lifecycle, and timing fields.
*
* @param field - ActiveRecord field builder.
* @returns Scheduled occurrence field definitions.
*/
static fields(field: FieldBuilder): {
id: import("../db/index.js").UlidField;
name: import("../db/index.js").StringField;
kind: import("../db/index.js").ChoiceStringField;
jobName: import("../db/index.js").StringField;
scheduledFor: import("../db/index.js").TimestampField;
status: import("../db/index.js").ChoiceStringField;
queueJobId: import("../db/index.js").StringField;
queueJobUuid: import("../db/index.js").CharUuidField;
attempts: import("../db/index.js").IntegerField;
maxTries: import("../db/index.js").IntegerField;
lastError: import("../db/index.js").TextField;
nextAttemptAt: import("../db/index.js").TimestampField;
claimedAt: import("../db/index.js").TimestampField;
dispatchedAt: import("../db/index.js").TimestampField;
startedAt: import("../db/index.js").TimestampField;
finishedAt: import("../db/index.js").TimestampField;
updatedAt: import("../db/index.js").TimestampField;
};
/**
* Atomically claims one scheduled minute using the model's unique index.
*
* @param claim - Due schedule identity and task metadata.
* @returns Newly claimed occurrence, or null when another process won.
*/
static claim(claim: ScheduledOccurrenceClaim): Promise<ScheduledOccurrence | null>;
id: string | null;
name: string | null;
kind: scheduler.ScheduledTaskKind | null;
jobName: string | null;
scheduledFor: Date | null;
status: scheduler.ScheduledOccurrenceStatus | null;
queueJobId: string | null;
queueJobUuid: string | null;
attempts: number | null;
maxTries: number | null;
lastError: string | null;
nextAttemptAt: Date | null;
claimedAt: Date | null;
dispatchedAt: Date | null;
startedAt: Date | null;
finishedAt: Date | null;
updatedAt: Date | null;
}
export {};
Queue lifecycle recorder
ts
import { type Database } from '../db/index.js';
import type { QueueLifecycleEvent } from '../queue/index.js';
/**
* Persists queue lifecycle events that originated from scheduled occurrences.
*/
export declare class ScheduledOccurrenceRecorder {
private readonly database;
/**
* Creates a recorder bound to one application database.
*
* @param database - Database containing scheduled occurrence records.
*/
constructor(database: Database);
/**
* Applies one queue event when it references a scheduled occurrence.
*
* @param event - Queue lifecycle event emitted by the worker or dispatcher.
*/
record(event: QueueLifecycleEvent): Promise<void>;
/**
* Maps one queue lifecycle event onto its persisted occurrence.
*
* @param occurrence - Scheduled occurrence being updated.
* @param event - Queue lifecycle event to apply.
*/
private applyEvent;
}
/**
* Formats an unknown error for durable scheduler diagnostics.
*
* @param error - Unknown thrown value.
* @returns Stack or human-readable error text.
*/
export declare function errorDetails(error: unknown): string;
Worker lifecycle
ts
import type * as scheduler from './contracts/index.js';
import { Scheduler } from './Scheduler.js';
/**
* Long-running minute-aligned process adapter around Scheduler.runDue().
*/
export declare class SchedulerWorker {
#private;
private readonly schedulerService;
/**
* Creates a scheduler worker with injectable timing dependencies.
*
* @param schedulerService - Scheduler core evaluated on every tick.
* @param options - Clock, sleeper, logger, and warning overrides.
*/
constructor(schedulerService: Scheduler, options?: scheduler.SchedulerWorkerOptions);
/**
* Runs immediately, then evaluates at each subsequent wall-clock minute.
*
* @throws Error when the same worker instance is started twice.
*/
start(): Promise<void>;
/**
* Requests graceful shutdown and interrupts the current minute wait.
*/
stop(): void;
/**
* Evaluates one scheduler minute and reports failures without ending work.
*/
private runTick;
}
/**
* Calculates the delay from one instant to the next UTC minute boundary.
*
* @param now - Current clock time.
* @returns Delay in milliseconds, always between one and sixty seconds.
*/
export declare function millisecondsUntilNextMinute(now: Date): number;
Inputs and results
ts
import type { QueueableJob } from '../../queue/index.js';
/**
* Supported scheduled task kinds.
*/
export type ScheduledTaskKind = 'job' | 'call';
/**
* Durable lifecycle states recorded for one scheduled occurrence.
*/
export type ScheduledOccurrenceStatus = 'claimed' | 'queued' | 'running' | 'retrying' | 'deferred' | 'succeeded' | 'failed';
/**
* Daily frequency supported by the initial scheduler implementation.
*/
export interface DailyScheduleFrequency {
/** Frequency discriminator reserved for future schedule types. */
type: 'daily';
/** Local wall-clock time in 24-hour HH:mm format. */
time: string;
}
/**
* Normalized public description of one registered schedule.
*/
export interface ScheduledTaskDefinition {
/** Stable task name used for deduplication and history. */
name: string;
/** Whether the task dispatches a job or executes an inline callback. */
kind: ScheduledTaskKind;
/** Daily frequency and local wall-clock time. */
frequency: DailyScheduleFrequency;
/** IANA timezone used to interpret the frequency. */
timezone: string;
/** Durable queue job name when known without invoking a factory. */
jobName?: string;
}
/**
* Zero-argument QueueableJob class accepted directly by Scheduler.job().
*
* Jobs with constructor parameters must use a fresh-job factory instead.
*/
export interface ScheduledJobClass {
/** Runtime class name used as the default durable schedule and queue name. */
readonly name: string;
/** Optional stable queue job name override. */
readonly jobName?: string;
/** Creates a fresh job without runtime constructor dependencies. */
new (): QueueableJob;
/**
* Rehydrates a queued instance from persisted job data.
*
* @param data - JSON-safe queue payload.
* @returns Rehydrated job instance.
*/
fromJSON(data: Record<string, unknown>): QueueableJob;
}
/**
* Zero-argument class or fresh-job factory accepted by Scheduler.job().
*/
export type ScheduledJobSource = ScheduledJobClass | (() => QueueableJob);
/**
* Short synchronous or asynchronous callback accepted by Scheduler.call().
*/
export type ScheduledCallHandler = () => unknown | Promise<unknown>;
/**
* Immediate scheduler failure raised while dispatching or running a due task.
*/
export interface SchedulerFailure {
/** Stable schedule name that failed. */
name: string;
/** Human-readable failure message suitable for logs and CLI output. */
error: string;
}
/**
* Summary returned after evaluating all tasks for one UTC minute.
*/
export interface SchedulerRunResult {
/** UTC minute evaluated by the scheduler. */
evaluatedFor: Date;
/** Time at which evaluation began. */
startedAt: Date;
/** Time at which evaluation finished. */
finishedAt: Date;
/** Registered definitions whose local schedule matched the minute. */
due: number;
/** Due occurrences atomically claimed by this scheduler process. */
claimed: number;
/** Claimed jobs successfully accepted by the queue. */
dispatched: number;
/** Claimed inline calls that completed successfully. */
completed: number;
/** Due occurrences already claimed by another process. */
skipped: number;
/** Immediate dispatch or inline-call failures. */
failures: SchedulerFailure[];
}
/**
* Logger used by scheduler workers and console adapters.
*/
export interface SchedulerLogger {
/** Writes normal scheduler progress. */
info(message: string): void;
/** Writes slow-tick or recoverable scheduler warnings. */
warn(message: string): void;
/** Writes scheduler failures. */
error(message: string, error?: unknown): void;
}
Worker options
ts
import type { SchedulerLogger } from './Scheduler.js';
/**
* Abort-aware sleep function used by the long-running scheduler worker.
*/
export type SchedulerSleep = (delayMs: number, signal: AbortSignal) => Promise<void>;
/**
* Runtime dependencies and logging overrides for SchedulerWorker.
*/
export interface SchedulerWorkerOptions {
/** Clock used to align and evaluate scheduler ticks. */
now?: () => Date;
/** Abort-aware sleeper used between minute boundaries. */
sleep?: SchedulerSleep;
/** Scheduler progress and error logger. */
logger?: SchedulerLogger;
/** Duration that triggers a slow-tick warning. */
slowTickWarningMs?: number;
}
Console adapter
ts
import type * as scheduler from './contracts/index.js';
/**
* Runs one framework scheduler console command.
*
* `scheduler:work` remains alive and evaluates schedules every minute. The
* other commands bootstrap, execute once, and close application resources.
*
* @param options - Application factory, bootstrap hook, and help overrides.
* @param argv - Command arguments without the Node executable or script path.
*/
export declare function runSchedulerConsole(options: scheduler.SchedulerConsoleOptions, argv?: string[]): Promise<void>;
/**
* Parses scheduler console positional arguments and long options.
*
* @param argv - Command arguments without the executable or script path.
* @returns Parsed command input.
*/
export declare function parseSchedulerConsoleArgs(argv: string[]): scheduler.ParsedSchedulerConsoleArgs;
Console options
ts
import type { Scheduler } from '../Scheduler.js';
import type { Logger } from '../../logging/index.js';
/**
* Parsed scheduler command name, positional arguments, and long options.
*/
export interface ParsedSchedulerConsoleArgs {
/** Command selected by the caller. */
command: string;
/** Positional command arguments. */
args: string[];
/** Parsed `--name=value` or `--name value` options. */
options: Record<string, string | boolean>;
}
/**
* Minimum application surface required by the framework scheduler console.
*/
export interface SchedulerConsoleApp {
/** Application scheduler with all application definitions registered. */
scheduler: Scheduler;
/** Application logger used by the long-running scheduler when available. */
log?: Logger;
/** Releases database, queue, and other process resources. */
close(): void | Promise<void>;
}
/**
* Application hooks and help customisation for scheduler console commands.
*/
export interface SchedulerConsoleOptions {
/** Resolves the active application instance after bootstrap. */
app: () => SchedulerConsoleApp;
/** Prepares schema, queue jobs, and schedule definitions. */
bootstrap?: () => void | Promise<void>;
/** Optional application-specific help text. */
helpText?: string;
/** Optional application-specific unknown-command message. */
unknownCommandMessage?: (command: string) => string;
}