Last Updated: November 2026 · Plugin API: 1.1 · Capability: scheduler
registry.scheduler runs plugin code on a timer: at a fixed interval, on a cron schedule, or once at a given time. Each run happens on one server node, even when several nodes share the database, so a nightly reset or a payout job never runs twice.
Declare "capabilities": ["scheduler"] in your manifest. Without it, every call throws PluginCapabilityError. See capabilities.md.
API
registry.scheduler.every(jobId, intervalMs, handler, { runOnStart?, timeoutMs? }): void
registry.scheduler.cron(jobId, expression, handler, { timezone?, timeoutMs? }): void
registry.scheduler.once(jobId, at: Date, handler, { timeoutMs? }?): void
registry.scheduler.cancel(jobId): Promise<boolean> // true when a job was removed
registry.scheduler.list(): Promise<PluginJobInfo[]>
type PluginJobHandler = (ctx: {
providerType: string;
jobId: string;
scheduledAt: Date; // when this run was due
signal: AbortSignal; // aborted when the run times out
}) => void | Promise<void>;
| Input | Rule |
|---|---|
jobId | ^[a-z0-9:_-]{1,64}$, unique per plugin. Registering the same id again replaces the job. |
intervalMs | Integer, 1 000 ms to 366 days. |
expression | Standard cron, 5 fields (m h dom mon dow) or 6 with seconds first, parsed with cron-parser. Aliases such as @daily work. |
timezone | IANA zone, default UTC. 0 9 * * * with Europe/Amsterdam fires at 09:00 Amsterdam time, DST included. |
at | A valid Date. A date in the past runs on the next tick. |
timeoutMs | 1 000 to 600 000 (10 min), default 60 000. |
| Jobs per plugin | At most 100. |
Invalid input throws a ValidationError synchronously, so a typo surfaces in register().
PluginJobInfo is { providerType, jobId, kind, schedule, nextRunAt, lastRunAt, lastStatus, lockOwner, lockUntil, createdAt, updatedAt }.
Example
import { definePlugin } from '@poker-engine/plugin-sdk';
const plugin = definePlugin({
register(registry) {
// Every Monday 00:00 UTC
registry.scheduler.cron('leaderboard:weekly-reset', '0 0 * * 1', async () => {
const top = await registry.storage.query('xp', { orderBy: 'weekly', limit: 100 });
await registry.storage.global.set('leaderboard:last-week', top);
});
// Every 5 minutes, and once right after activation
registry.scheduler.every('cache:refresh', 5 * 60_000, refreshCache, { runOnStart: true });
// Long job: stop when the signal aborts
registry.scheduler.cron('digest', '5 0 * * *', async ({ signal }) => {
for (const batch of await loadBatches()) {
if (signal.aborted) return;
await processBatch(batch);
}
}, { timeoutMs: 5 * 60_000 });
},
});
export const { register } = plugin;
How it runs
- Register in
register(). Handlers live in memory on each node that loaded the plugin; the schedule lives in theplugin_jobstable. Every node loads the plugin, so every node has the handler and any of them can run the job. A job registered later (for exampleonce()from a route handler) only exists on the node that registered it, and only that node can run it. - Tick loop. Each node checks for due jobs every 15 seconds, so that is the effective granularity: an
every(1000)job runs about every 15 s. - One run per cluster (the lease). For each due job a node runs:
UPDATE plugin_jobs SET lock_owner = $node, lock_until = now() + $lease WHERE provider_type = $p AND job_id = $j AND next_run_at <= now() AND (lock_until IS NULL OR lock_until < now()) RETURNING *
Postgres serialises concurrent updates on the row and re-checks the condition, so only one node gets the row back; the others skip it. The lease is the job’s timeout plus a 5 s grace, so the owner writes its result before anyone else may claim the row. - After the run the owner sets
last_run_at,last_statusand the nextnext_run_at, and clears the lease.everyjobs move to the next slot on their grid (due + k × interval), skipping slots missed during downtime instead of running them all.cronjobs move to the next cron time.oncejobs setnext_run_atto null and stay listed with their status. - Crashes. If a node dies mid-run, the lease expires and the next tick on any node runs the job again. Write handlers so a repeated run is harmless (use idempotency keys for wallet credits).
- Restarts. Rows survive restarts. Re-registering a job with the same schedule keeps its
next_run_at, so a restarting node neither resets nor re-triggers it; a changed schedule (or kind) reschedules it.runOnStarttherefore runs once when the job is first created (activation), not on every boot. A job that was due while the cluster was down runs on the first tick.
Status, errors and timeouts
last_status is one of:
| Value | Meaning |
|---|---|
ok | The handler resolved. |
error:<message> | The handler threw or rejected (message cut to 500 characters). |
timeout | The handler did not settle within timeoutMs. Its signal is aborted; the run is not awaited further. |
Errors and timeouts each count +1 against the plugin’s circuit breaker (50 errors in 5 minutes auto-disables the plugin).
Lifecycle
| Event | Jobs |
|---|---|
register() | Recorded in memory only. |
| Activation, startup load, upgrade | Persisted to plugin_jobs; due and runOnStart jobs run on the next tick. Calls made after this persist immediately. |
| Deactivate, failed load, rollback, auto-disable | Handlers dropped and the plugin’s rows deleted. |
cancel(jobId) | That job’s handler and row removed. |
Admin
In Extensions › Plugins, View details on the plugin’s row opens a side panel with a Scheduled jobs section: each job with its Schedule, Last run, Next run and a status (Last run OK, Last run failed or Not run yet). GET /api/v1/admin/plugins/:id/jobs (admin) returns { success: true, data: { jobs: PluginJobInfo[] } }. The plugin detail GET /api/v1/admin/plugins/:id includes the same list as jobs.
Testing
createTestRegistry() from @poker-engine/plugin-sdk/testing records jobs in registry.test.jobs; await registry.test.runJob(jobId) calls a handler now with a fresh signal.
const registry = createTestRegistry();
await plugin.register(registry);
expect(registry.test.jobs.get('leaderboard:weekly-reset')?.schedule).toBe('0 0 * * 1');
await registry.test.runJob('leaderboard:weekly-reset');
Related files
| File | Purpose |
|---|---|
src/core/plugins/plugin-scheduler.ts | Registry namespace, lease, tick loop |
prisma/schema.prisma (PluginJob) | plugin_jobs table |
src/api/routes/admin/plugins.routes.ts | GET /admin/plugins/:id/jobs |
See also: Capabilities, Lifecycle, Admin: Plugins, Plugin Development Guide.