Reference

Baker

Holds a set of named jobs. You add jobs, control them by name, and optionally persist them.

On this page
import Baker from "cronbake";

const baker = Baker.create({ autoStart: true });

Options

All are optional. new Baker(options) takes the same object.

autoStart boolean Default false Next release
Start each new job when it’s added, unless it sets start: false. Also starts all jobs once when the baker finishes initialising, so await ready() before adding jobs that opt out.
onError (error: Error, jobName: string) => void
Called when a job’s callback fails and the job has no onError of its own. Without either one, the failure goes to logger.warn().
logger Logger Default console
Used for baker messages and for any job without its own logger. See Logging.
enableMetrics boolean Default true
When false, getMetrics() returns zeros, getHistory() returns an empty list, and metrics are left out of the persisted state.
schedulerConfig.useCalculatedTimeouts boolean Default true
Use one precise timer per job. Set to false to poll instead. See Scheduler modes.
schedulerConfig.pollingInterval number Default 1000
Milliseconds between checks when polling. Must be more than 0 and at most 2,147,483,647.
schedulerConfig.maxHistoryEntries number Default 100
History limit for jobs that don’t set maxHistory.
persistence.enabled boolean Default false
Turn persistence on. See Persistence.
persistence.filePath string Default "./cronbake-state.json"
Where the file provider writes. Ignored if you pass a provider.
persistence.autoRestore boolean Default true
Load saved jobs when the baker is created.
persistence.provider PersistenceProvider
Where to save and load state. Takes precedence over strategy and filePath.
persistence.strategy "file" | "redis" | "custom" Default "file"
With "file", a file provider is created for you. The other two need a provider, or the constructor throws.
persistence.redis { key?: string }
Reserved. Nothing reads this at the moment, so set the key on RedisPersistenceProvider instead.

Managing jobs

add()

add<T extends string = string>(options: CronOptions<T>): ICron<T>

Creates a job and returns it. Throws if the expression is invalid, or if the name is taken by a job you added earlier. A job restored from persistence is replaced instead. See CronOptions for what you can pass.

remove()

remove(name: string): void

Stops the job, fires its onComplete, and removes it from the baker. Does nothing if the name doesn’t exist.

destroy()

destroy(name: string): void

Identical to remove().

destroyAll()

destroyAll(): void

Removes every job, firing onComplete on each.

getJobNames()

getJobNames(): string[]

The names of all jobs, in the order they were added.

getAllJobs()

getAllJobs(): Map<string, ICron>

A new Map of names to jobs. Changing the map doesn’t affect the baker, but the jobs in it are the real ones.

Controlling jobs

These do nothing if the name doesn’t exist, or if the job’s state doesn’t allow the change. Job lifecycle has the full table.

bake()

bake(name: string): void

Starts a stopped or paused job. If the job’s schedule has no future date, this throws.

stop()

stop(name: string): void

Stops a running or paused job. A run in progress finishes.

pause()

pause(name: string): void

Pauses a running job. A run in progress finishes.

resume()

resume(name: string): void

Resumes a paused job from its next tick after the current time.

bakeAll()

bakeAll(): void

Starts all jobs, highest priority first Next release. If a job’s schedule has no future date, this throws and later jobs aren’t started.

stopAll()

stopAll(): void

Stops all jobs.

pauseAll()

pauseAll(): void

Pauses all running jobs.

resumeAll()

resumeAll(): void

Resumes all paused jobs.

Inspecting jobs

None of these throw for an unknown name. The fallback for each is listed below.

getStatus()

getStatus(name: string): Status

"stopped", "running" or "paused". Returns "stopped" for an unknown name.

isRunning()

isRunning(name: string): boolean

Whether the job is scheduled, which isn’t the same as its callback executing right now. Returns false for an unknown name.

nextExecution()

nextExecution(name: string): Date

The next tick. Returns the current time if the job isn’t scheduled or doesn’t exist, so check isRunning() first.

lastExecution()

lastExecution(name: string): Date

The start of the most recent run. If the job has never run, this is the last time its schedule matched. Returns the current time for an unknown name.

remaining()

remaining(name: string): number

Milliseconds until the next tick, or 0 if the job isn’t scheduled or doesn’t exist.

time()

time(name: string): number

The same as remaining().

getMetrics()

getMetrics(name: string): JobMetrics

A copy of the job’s metrics. Returns zeros for an unknown name, or when enableMetrics is off.

getHistory()

getHistory(name: string): ExecutionHistory[]

A copy of the job’s recent runs, newest first. Returns an empty list for an unknown name, or when enableMetrics is off.

resetAllMetrics()

resetAllMetrics(): void

Clears metrics and history for all jobs. Does nothing when enableMetrics is off.

Persistence

ready()

ready(): Promise<void>

Resolves when the first restore has finished, or right away if there isn’t one. Rejects if that restore fails. Await this before adding jobs when persistence or autoStart is on.

saveState()

saveState(): Promise<void>

Writes all jobs with persist enabled to the provider. Does nothing if persistence is off. Rejects if the write fails.

restoreState()

restoreState(): Promise<void>

Loads jobs from the provider, skipping any name that already exists. Does nothing if persistence is off, or if a restore is already in progress. Rejects if the load fails or the state is malformed.

Static methods

Baker.create()

static create(options?: IBakerOptions): Baker

The same as new Baker(options).

esc

Try overlap, restore or timezone.