Reference
Baker
Holds a set of named jobs. You add jobs, control them by name, and optionally persist them.
On this page
- Options
- Managing jobs
- add()
- remove()
- destroy()
- destroyAll()
- getJobNames()
- getAllJobs()
- Controlling jobs
- bake()
- stop()
- pause()
- resume()
- bakeAll()
- stopAll()
- pauseAll()
- resumeAll()
- Inspecting jobs
- getStatus()
- isRunning()
- nextExecution()
- lastExecution()
- remaining()
- time()
- getMetrics()
- getHistory()
- resetAllMetrics()
- Persistence
- ready()
- saveState()
- restoreState()
- Static methods
- Baker.create()
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 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 onError of its own. Without either one, the failure goes to logger.warn().logger Logger Default console enableMetrics boolean Default true false, getMetrics() returns zeros, getHistory() returns an empty list, and metrics are left out of the persisted state.schedulerConfig.useCalculatedTimeouts boolean Default true false to poll instead. See Scheduler modes.schedulerConfig.pollingInterval number Default 1000 schedulerConfig.maxHistoryEntries number Default 100 maxHistory.persistence.enabled boolean Default false persistence.filePath string Default "./cronbake-state.json" provider.persistence.autoRestore boolean Default true persistence.provider PersistenceProvider strategy and filePath.persistence.strategy "file" | "redis" | "custom" Default "file" "file", a file provider is created for you. The other two need a provider, or the constructor throws.persistence.redis { key?: string } 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): voidStops the job, fires its onComplete, and removes it from the baker. Does nothing if the name doesn’t exist.
destroy()
destroy(name: string): voidIdentical to remove().
destroyAll()
destroyAll(): voidRemoves 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): voidStarts a stopped or paused job. If the job’s schedule has no future date, this throws.
stop()
stop(name: string): voidStops a running or paused job. A run in progress finishes.
pause()
pause(name: string): voidPauses a running job. A run in progress finishes.
resume()
resume(name: string): voidResumes a paused job from its next tick after the current time.
bakeAll()
bakeAll(): voidStarts all jobs, highest priority first . If a job’s schedule has no future date, this throws and later jobs aren’t started.
stopAll()
stopAll(): voidStops all jobs.
pauseAll()
pauseAll(): voidPauses all running jobs.
resumeAll()
resumeAll(): voidResumes 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): booleanWhether 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): DateThe next tick. Returns the current time if the job isn’t scheduled or doesn’t exist, so check isRunning() first.
lastExecution()
lastExecution(name: string): DateThe 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): numberMilliseconds until the next tick, or 0 if the job isn’t scheduled or doesn’t exist.
time()
time(name: string): numberThe same as remaining().
getMetrics()
getMetrics(name: string): JobMetricsA 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(): voidClears 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): BakerThe same as new Baker(options).