Skip to content

@plinthjs/scheduling ​

Plinth's task scheduler. A five-field cron expression parser/matcher, a fluent scheduled Event (with lifecycle hooks, run-time gates, and overlap prevention), and the Schedule registry that runs the events due at a given instant.

Every time-aware method takes the reference Date explicitly, so scheduling is deterministic in tests: there is no hidden wall-clock read.

Usage ​

ts
import { Schedule, Weekday } from '@plinthjs/scheduling'

const schedule = new Schedule()

schedule.call(() => sendDigest(), 'digest').dailyAt('13:30')
schedule.command('backup:run', () => runBackup()).weeklyOn(Weekday.Sunday, '02:00')
schedule.call(() => pollQueue()).everyFiveMinutes()

// Drive the kernel tick from a per-minute cron, passing the current instant in. This honours
// run-time gates (when/skip) and overlap locks, and routes per-event failures to onFailure.
await schedule.runDueEvents(new Date())

// Inspect what would fire without running it.
const due = schedule.dueEvents(new Date(Date.UTC(2026, 5, 4, 13, 30)))

Lifecycle hooks, run-time gates, and overlap prevention ​

ts
schedule
  .call(() => syncInventory(), 'inventory:sync')
  .everyFiveMinutes()
  .when(() => featureEnabled('inventory')) // run only if every when() passes …
  .skip(() => isMaintenanceWindow()) // … and no skip() does
  .withoutOverlapping() // skip a tick while a prior run is still in flight
  .before(() => log('starting'))
  .onSuccess(() => log('done'))
  .onFailure((error) => report(error))
  .after(() => log('finished')) // runs on success or failure

withoutOverlapping() is backed by an injectable LockStore ({ acquire(key): boolean; release(key): void }). Schedule shares one InMemoryLockStore across its events by default; pass your own (e.g. a Redis-backed store) to new Schedule(lockStore) to coordinate overlap across processes.

Schedule.run(now) remains as a bare runner that ignores gates and locks and propagates the first error; prefer runDueEvents(now) for the full kernel tick.

Cron expressions directly ​

ts
import { CronExpression } from '@plinthjs/scheduling'

const cron = new CronExpression('*/15 9-17 * * 1-5') // every 15 min, 9-5, weekdays
cron.isDue(new Date(Date.UTC(2026, 5, 4, 9, 15))) // true
cron.nextRunDate(new Date(Date.UTC(2026, 5, 4, 9, 1))) // 09:15

Supported field syntax: *, */step, ranges a-b, lists a,b,c, and the combo a-b/step. When both the day-of-month and day-of-week fields are restricted, a date matches if either matches (the standard cron convention).

Cadence helpers ​

everyMinute, everyFiveMinutes, everyTenMinutes, everyThirtyMinutes, hourly, hourlyAt(min), daily, dailyAt('HH:MM'), weekly, weeklyOn(day, 'HH:MM'), monthly, and cron(expr) for an explicit expression.

Released under the MIT License.