Skip to content

Scheduling ​

Introduction ​

The scheduler lets you describe recurring work in code instead of in a crontab. You register tasks on a Schedule, say how often each one runs, and then call the schedule once a minute. It runs whichever tasks are due at that moment.

The scheduler does not own a clock. Every time-aware method takes the current Date you give it, so it behaves the same in a test as in production. It also does not start a loop on its own: you decide what calls it every minute (a loop in your process, a system cron entry, a console command). See Running the scheduler.

bash
pnpm add @plinthjs/scheduling

Defining scheduled tasks ​

Create a Schedule and add tasks with call(). Each call returns an Event that you configure with a fluent chain. A new event is due every minute until you pick a frequency.

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

const schedule = new Schedule()

schedule.call(() => sendDigest(), 'digest').dailyAt('13:30')
schedule.call(() => pruneSessions(), 'sessions:prune').hourly()

The second argument is an optional name. The name identifies the task in lock keys, and description on the event returns it. Give every task a unique name, especially if you use overlap or one-server locks.

There are three ways to add a task:

ts
schedule.call(() => doWork(), 'work') // run a function
schedule.command('backup:run', () => runBackup()) // a function with a name (the name is required)
schedule.exec('node', ['scripts/report.js', '--daily']) // run a shell command

command() only labels the callback with a name. It does not look anything up, so if you want to run a console command, call the kernel yourself:

ts
schedule.command('migrate:status', () => kernel.call('migrate:status')).daily()

A task callback may be async. Whatever it returns is available to the output hooks if it is a string.

Running shell commands ​

exec(command, args) runs the command through a shell and resolves with its standard output. A non-zero exit code makes the task fail with an error that contains the exit code and standard error. The task is named after the full command line.

ts
const event = schedule.exec('echo', ['hi']).everyMinute()
event.description // => 'echo hi'

Because the arguments are joined into a single shell string, do not pass untrusted input as arguments.

Setting the frequency ​

Frequency helpers replace the event's cron expression. Chain them directly after call().

MethodCron expression
everyMinute()* * * * *
everyTwoMinutes()*/2 * * * *
everyFiveMinutes()*/5 * * * *
everyTenMinutes()*/10 * * * *
everyFifteenMinutes()*/15 * * * *
everyThirtyMinutes()*/30 * * * *
hourly()0 * * * *
hourlyAt(17)17 * * * *
daily()0 0 * * *
dailyAt('13:30')30 13 * * *
twiceDaily(1, 13)0 1,13 * * *
weekly()0 0 * * 0
weeklyOn(Weekday.Monday, '8:15')15 8 * * 1
monthly()0 0 1 * *
monthlyOn(15, '4:00')0 4 15 * *
lastDayOfMonth('23:00')runs at 23:00 on the last day
quarterly()0 0 1 1,4,7,10 *
yearly()0 0 1 1 *

Weekday is an object of day numbers (Sunday is 0 through Saturday is 6).

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

schedule.call(() => sendReport(), 'weekly-report').weeklyOn(Weekday.Monday, '08:15')

For anything else, pass a cron expression to cron():

ts
schedule.call(() => sync(), 'sync').cron('*/15 9-17 * * 1-5') // every 15 minutes, 09:00-17:59, Monday to Friday

WARNING

Times are UTC unless you set a time zone. dailyAt('13:30') fires at 13:30 UTC, not in the server's local zone. To use another zone, give the event (or the whole schedule) an IANA name: schedule.call(task).dailyAt('09:00').timezone('America/New_York') or schedule.useTimezone('Asia/Kolkata'). The cadence helpers and the between, unlessBetween and lastDayOfMonth checks are then evaluated in that zone, daylight saving included.

Refining a frequency ​

at(), days(), weekdays() and weekends() change one part of the current expression, so they combine with a frequency helper.

ts
schedule
  .call(() => report(), 'report')
  .daily()
  .at('9:05') // 5 9 * * *
schedule
  .call(() => report(), 'weekday-report')
  .dailyAt('9:05')
  .weekdays() // 5 9 * * 1-5
schedule
  .call(() => report(), 'weekend-report')
  .dailyAt('10:00')
  .weekends() // 0 10 * * 0,6
schedule
  .call(() => report(), 'mwf')
  .hourly()
  .days(1, 3, 5) // 0 * * * 1,3,5

Times use the form H:MM or HH:MM, and invalid times or days throw when you configure the event rather than when it runs.

Cron expressions directly ​

CronExpression is the parser behind every event. It supports *, a step (*/15), a range (9-17), a list (1,3,5) and a ranged step (0-30/10) in each of five fields: minute, hour, day of month, month, day of week.

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

const cron = new CronExpression('*/15 9-17 * * 1-5')

cron.isDue(new Date(Date.UTC(2026, 5, 4, 9, 15))) // => true
cron.nextRunDate(new Date(Date.UTC(2026, 5, 4, 9, 1))) // => 2026-06-04T09:15:00.000Z

When both the day-of-month and the day-of-week fields are restricted, a date matches if either one matches. An invalid expression throws with a message that names the field.

Restricting when a task runs ​

A task is "due" when its cron expression matches the current minute. You can add conditions that must also hold.

Truth tests ​

when() runs the task only if the callback returns true. skip() skips the task if the callback returns true. Callbacks may be async, and every when() must pass and no skip() may match.

ts
schedule
  .call(() => syncInventory(), 'inventory:sync')
  .everyFiveMinutes()
  .when(() => featureEnabled('inventory'))
  .skip(() => isMaintenanceWindow())

Time windows ​

between(start, end) runs the task only inside the window, and unlessBetween(start, end) skips it inside the window. Both are inclusive and take HH:MM strings in the event's time zone (UTC by default). A window may cross midnight.

ts
schedule
  .call(() => poll(), 'poll')
  .everyMinute()
  .between('09:00', '17:00')
schedule
  .call(() => heavyJob(), 'heavy')
  .everyMinute()
  .unlessBetween('13:00', '14:00')
schedule
  .call(() => overnight(), 'overnight')
  .everyMinute()
  .between('22:00', '02:00')

Environments ​

environments(...names) limits a task to the named environments. Tell the schedule which environment it is running in with useEnvironment(). The setting applies to events added before and after the call.

ts
const schedule = new Schedule().useEnvironment(process.env['NODE_ENV'] ?? 'production')

schedule
  .call(() => sendDigest(), 'digest')
  .daily()
  .environments('production')

If no environment is set, the restriction does not apply.

WARNING

when(), skip(), between(), unlessBetween() and environments() are checks. Schedule.runIfDue(now) (also available as runDueEvents(now)) and Event.runIfDue(now) evaluate them. Schedule.run() and Event.run() are unconditional: Event.run() ignores the cron expression and every check, and Schedule.run() ignores the checks. Drive the schedule with runIfDue().

Preventing overlap ​

If a task can take longer than its interval, ask the scheduler not to start a second copy while the first is still running.

ts
schedule
  .call(async () => importFeed(), 'feed:import')
  .everyMinute()
  .withoutOverlapping()

The scheduler takes a lock named after the task before running it and releases the lock when the task finishes, whether it succeeded or failed. If the lock is already held, that run is skipped. The lock expires after 24 hours as a safety net. Pass a number of minutes to change that: withoutOverlapping(10).

Locks and multiple servers ​

A Schedule keeps its locks in a LockStore. The default, InMemoryLockStore, lives inside one process, so it prevents overlap only within that process. To coordinate several processes or servers, pass a store that all of them share:

ts
import { Schedule } from '@plinthjs/scheduling'
import type { LockStore } from '@plinthjs/scheduling'

class SharedLockStore implements LockStore {
  acquire(key: string, ttlSeconds?: number): boolean {
    // Return true only if you atomically created the key. Use a store all servers can reach.
    return claimKey(key, ttlSeconds)
  }

  release(key: string): void {
    deleteKey(key)
  }
}

const schedule = new Schedule(new SharedLockStore())

onOneServer() uses the same store to make sure that, when several servers run the same schedule at the same minute, only the first one to acquire the lock runs the task. The lock key includes the task name and the minute, and it expires after 60 seconds.

ts
schedule
  .call(() => sendDigest(), 'digest')
  .dailyAt('13:30')
  .onOneServer()

With the default in-memory store each process has its own locks, so onOneServer() and withoutOverlapping() only work across processes or servers when you pass a shared LockStore to new Schedule(store). Using either with the default store emits a one-time PlinthSchedulingWarning (route it elsewhere with setSchedulingWarningHandler).

Lifecycle hooks ​

Attach functions that run around a task. All of them may be async.

ts
schedule
  .call(() => backup(), 'backup')
  .daily()
  .before(() => log('starting'))
  .onSuccess(() => log('done'))
  .onFailure((error) => report(error))
  .after(() => log('finished'))

The order for one run is: before pings, before, the task, output sinks, onSuccess, then after and the after pings. If the task throws, onFailure hooks receive the error and after still runs. after and the after pings always run, success or failure.

Handling task output ​

When a task returns a string (as exec() tasks do), the string is passed to the output sinks. A sink is a function, so you decide where output goes.

ts
import { appendFile } from 'node:fs/promises'

schedule
  .exec('node', ['scripts/report.js'])
  .daily()
  .sendOutputTo((output) => console.log(output))
  .appendOutputTo((output) => appendFile('storage/logs/report.log', output))

sendOutputTo() replaces any sinks added so far, and appendOutputTo() adds another. A task that returns anything other than a string produces no output. Sinks run only after the task succeeds.

Pings ​

Pings are hooks meant for health-check or heartbeat URLs. You supply the function that makes the request, so you can use any HTTP client.

ts
schedule
  .call(() => backup(), 'backup')
  .daily()
  .pingBefore(() => fetch('https://hc.example.com/ping/backup/start'))
  .thenPing(() => fetch('https://hc.example.com/ping/backup'))
  .pingOnFailure(() => fetch('https://hc.example.com/ping/backup/fail'))
MethodWhen it runs
pingBefore(fn)Before the task starts
thenPing(fn)After the task, whether it succeeded or failed
pingOnSuccess(fn)Only when the task succeeds
pingOnFailure(fn)Only when the task fails
pingBeforeIf(condition, fn)Like pingBefore, only if condition is true
thenPingIf(condition, fn)Like thenPing, only if condition is true

The two conditional variants take a plain boolean that is evaluated when you define the schedule, so you can switch pings on from configuration:

ts
const monitoring = process.env['HEARTBEAT_URL'] !== undefined

schedule
  .call(() => backup(), 'backup')
  .daily()
  .thenPingIf(monitoring, () => fetch(process.env['HEARTBEAT_URL']!))

Running the scheduler ​

runIfDue(now) (alias runDueEvents) finds every task due at now, checks its conditions, and runs it. A task that throws does not stop the others: after its onFailure hooks run, the loop moves on, and once every task has run the failures are rethrown together as an AggregateError (error.errors lists them in order). Tasks run one after another, in the order you defined them.

ts
await schedule.runDueEvents(new Date())

Call it once per minute. There are two common ways.

From a loop in your process ​

ts
function startScheduler(schedule: Schedule): void {
  const tick = (): void => {
    void schedule.runDueEvents(new Date())
    setTimeout(tick, 60_000 - (Date.now() % 60_000)) // wake at the start of the next minute
  }
  setTimeout(tick, 60_000 - (Date.now() % 60_000))
}

From a console command ​

Wrap the call in a console command and run it from the system cron every minute. This is the right choice when the application is not a long-running process.

ts
import { Command } from '@plinthjs/console'

export class ScheduleRunCommand extends Command {
  static override signature = 'schedule:run'
  static override description = 'Run the scheduled tasks that are due'

  override async handle(): Promise<number> {
    await schedule.runDueEvents(new Date())
    return 0
  }
}
bash
* * * * * cd /path/to/app && npx tsx src/console.ts schedule:run

If you want an error to surface instead of being swallowed, call event.run(now) yourself. It runs the task, fires the hooks and rethrows. schedule.run(now) runs every due task without checking conditions and stops at the first failure.

Inspecting the schedule ​

ts
schedule.events() // every registered Event
schedule.dueEvents(new Date()) // the events whose cron expression matches this minute
schedule.collect() // the events as a Collection

const event = schedule.events()[0]!
event.expression // => '30 13 * * *'
event.description // => 'digest'
event.nextRunDate(new Date()) // the next matching minute

dueEvents() looks only at the cron expression, not at conditions. That makes it a cheap way to list what would fire.

Testing scheduled tasks ​

Because you pass the time in, a test does not wait for anything. Build the date, run the schedule, and assert on what happened.

ts
import { Schedule } from '@plinthjs/scheduling'
import { expect, it } from 'vitest'

it('sends the digest at 13:30', async () => {
  const sent: string[] = []
  const schedule = new Schedule()
  schedule.call(() => sent.push('digest'), 'digest').dailyAt('13:30')

  await schedule.runDueEvents(new Date(Date.UTC(2026, 5, 4, 13, 29)))
  expect(sent).toEqual([])

  await schedule.runDueEvents(new Date(Date.UTC(2026, 5, 4, 13, 30)))
  expect(sent).toEqual(['digest'])
})

Time windows and lastDayOfMonth() read the current time from the event's clock, which defaults to the system time. Pin it with useClock() so your test controls it.

ts
schedule
  .call(() => poll(), 'poll')
  .everyMinute()
  .between('09:00', '17:00')
  .useClock(() => new Date(Date.UTC(2026, 5, 4, 12, 0)))

To test overlap behaviour, give the schedule an InMemoryLockStore (the default) and run the same event twice at once. Only the first run enters the callback.

Tasks usually dispatch work to a queue, send mail, or run console commands. See Queues, Mail and Console.

Released under the MIT License.