croner
Version:
Trigger functions and/or evaluate cron expressions in JavaScript. No dependencies. Most features. All environments.
694 lines (691 loc) • 22.9 kB
TypeScript
// Generated by dts-bundle-generator v9.5.1
/**
* Cron pattern mode for controlling precision level
*/
export type CronMode = "auto" | "5-part" | "6-part" | "7-part" | "5-or-6-parts" | "6-or-7-parts";
/**
* Create a CronPattern instance from pattern string ('* * * * * *')
* @constructor
* @param {string} pattern - Input pattern
* @param {string} timezone - Input timezone, used for '?'-substitution
* @param {object} options - Cron options including mode
*/
export declare class CronPattern {
pattern: string;
timezone?: string;
mode: CronMode;
alternativeWeekdays: boolean;
sloppyRanges: boolean;
second: number[];
minute: number[];
hour: number[];
day: number[];
month: number[];
dayOfWeek: number[];
year: number[];
lastDayOfMonth: boolean;
lastWeekday: boolean;
nearestWeekdays: number[];
starDOM: boolean;
starDOW: boolean;
starYear: boolean;
useAndLogic: boolean;
constructor(pattern: string, timezone?: string, options?: {
mode?: CronMode;
alternativeWeekdays?: boolean;
sloppyRanges?: boolean;
});
/**
* Parse current pattern, will throw on any type of failure
* @private
*/
private parse;
/**
* Convert current part (seconds/minutes etc) to an array of 1 or 0 depending on if the part is about to trigger a run or not.
*/
private partToArray;
/**
* After converting JAN-DEC, SUN-SAT only 0-9 * , / - are allowed, throw if anything else pops up
* @throws On error
*/
private throwAtIllegalCharacters;
/**
* Nothing but a number, potentially with a modifier, left - handle that
*
* @param conf Current part, expected to be a number, as a string
* @param type One of "seconds", "minutes" etc
* @param valueIndexOffset -1 for day of month, and month, as they start at 1. 0 for seconds, hours, minutes
*/
private handleNumber;
/**
* Set a specific value for a specific part of the CronPattern.
*
* @param part The specific part of the CronPattern, e.g., "second", "minute", etc.
* @param index The index to modify.
* @param value The value to set, typically 0 or 1, in case of "nth weekday" it will be the weekday number used for further processing
*/
private setPart;
/**
* Validates that a parsed number is not NaN.
* Throws a TypeError with a descriptive message if the value is NaN.
*
* @param value - The value to validate
* @param errorMessage - The error message to throw if validation fails
* @throws {TypeError} If the value is NaN
* @private
*/
private validateNotNaN;
/**
* Validates that a range is valid (lower <= upper) and that steps are valid (> 0 and <= array length).
*
* @param lower - Lower bound of range
* @param upper - Upper bound of range
* @param steps - Optional step value to validate
* @param type - The type of pattern part being validated
* @param conf - The original configuration string for error messages
* @throws {TypeError} If validation fails
* @private
*/
private validateRange;
/**
* Take care of ranges with stepping (e.g. 3-23/5)
*
* @param conf Current part, expected to be a string like 3-23/5
* @param type One of "seconds", "minutes" etc
* @param valueIndexOffset -1 for day of month, and month, as they start at 1. 0 for seconds, hours, minutes
*/
private handleRangeWithStepping;
private extractNth;
/**
* Take care of ranges (e.g. 1-20)
*
* @param conf - Current part, expected to be a string like 1-20, can contain L for last
* @param type - One of "seconds", "minutes" etc
* @param valueIndexOffset - -1 for day of month, and month, as they start at 1. 0 for seconds, hours, minutes
*/
private handleRange;
/**
* Handle stepping (e.g. * / 14)
*
* @param conf Current part, expected to be a string like * /20 (without the space)
* @param type One of "seconds", "minutes" etc
*/
private handleStepping;
/**
* Replace day name with day numbers
*
* @param conf Current part, expected to be a string that might contain sun,mon etc.
*
* @returns Conf with 0 instead of sun etc.
*/
private replaceAlphaDays;
/**
* Replace day name with day numbers (Quartz mode)
* In Quartz mode: Sunday=1, Monday=2, ..., Saturday=7
*
* @param conf Current part, expected to be a string that might contain sun,mon etc.
*
* @returns Conf with Quartz-style numbering
*/
private replaceAlphaDaysQuartz;
/**
* Replace month name with month numbers
*
* @param conf Current part, expected to be a string that might contain jan,feb etc.
*
* @returns conf with 0 instead of sun etc.
*/
private replaceAlphaMonths;
/**
* Replace nicknames with actual cron patterns
*
* @param pattern Pattern, may contain nicknames, or not
*
* @returns Pattern, with cron expression insted of nicknames
*/
private handleNicknames;
/**
* Handle the nth weekday of the month logic using hash sign (e.g. FRI#2 for the second Friday of the month)
*
* @param index Weekday, example: 5 for friday
* @param nthWeekday bitmask, 2 (0x00010) for 2nd friday, 31 (ANY_OCCURRENCE, 0b100000) for any day
*/
private setNthWeekdayOfMonth;
}
export type CatchCallbackFn = (e: unknown, job: Cron) => void;
export type ProtectCallbackFn = (job: Cron) => void;
/**
* Options for configuring cron jobs.
*
* @interface
*/
export interface CronOptions<T = undefined> {
/**
* The name of the cron job. If provided, the job will be added to the
* `scheduledJobs` array, allowing it to be accessed by name.
*/
name?: string;
/**
* If true, the job will be paused initially.
* @default false
*/
paused?: boolean;
/**
* If true, the job will be stopped permanently.
* @default false
*/
kill?: boolean;
/**
* If true, errors thrown by the job function will be caught.
* If a function is provided, it will be called with the error and the job instance.
* @default false
*/
catch?: boolean | CatchCallbackFn;
/**
* If true, the underlying timer will be unreferenced, allowing the Node.js
* process to exit even if the job is still running.
* @default false
*/
unref?: boolean;
/**
* The maximum number of times the job will run.
* @default Infinity
*/
maxRuns?: number;
/**
* The minimum interval between job executions, in seconds.
* @default 1
*/
interval?: number;
/**
* If true, prevents the job from running if the previous execution is still in progress.
* If a function is provided, it will be called if the job is blocked.
* @default false
*/
protect?: boolean | ProtectCallbackFn;
/**
* The date and time at which the job should start running.
*/
startAt?: string | Date | CronDate<T>;
/**
* The date and time at which the job should stop running.
*/
stopAt?: string | Date | CronDate<T>;
/**
* The timezone for the cron job.
*/
timezone?: string;
/**
* The UTC offset for the cron job, in minutes.
*/
utcOffset?: number;
/**
* If true, uses AND logic when combining day-of-month and day-of-week.
* If false, uses OR logic for combining day-of-month and day-of-week (legacy behavior).
* @default false
*/
domAndDow?: boolean;
/**
* @deprecated Use domAndDow instead. This option will be removed in a future version.
* If true, enables legacy mode (OR logic) for compatibility with older cron implementations.
* Offset the scheduled date by a number of days.
* Positive values shift the date forward, negative values shift it backward.
* For example, dayOffset: -1 schedules the job one day before the pattern match.
* @default 0
*/
dayOffset?: number;
/**
* If true, enables legacy mode for compatibility with older cron implementations.
* @default true
*/
legacyMode?: boolean;
/**
* Specifies the cron pattern mode to use for parsing and execution.
*
* - "auto": Automatically detect pattern format (default behavior)
* - "5-part": Traditional 5-field cron (minute-level precision, seconds forced to 0, years wildcarded)
* - "6-part": Extended 6-field cron (second-level precision, years wildcarded)
* - "7-part": Full 7-field cron (second-level and year-specific precision)
* - "5-or-6-parts": Accept 5 or 6 field patterns (years wildcarded)
* - "6-or-7-parts": Accept 6 or 7 field patterns (no additional constraints)
*
* @default "auto"
*/
mode?: CronMode;
/**
* An optional context object that will be passed to the job function.
*/
context?: T;
/**
* If true, enables alternative weekday numbering (Quartz mode).
* In standard mode (false): Sunday=0, Monday=1, ..., Saturday=6
* In Quartz mode (true): Sunday=1, Monday=2, ..., Saturday=7
* @default false
*/
alternativeWeekdays?: boolean;
/**
* If true, allows non-standard stepping formats for backward compatibility.
* When false (default), only wildcard (*\/step) or range (min-max\/step) formats are allowed.
* When true, allows numeric prefix formats like /10, 5/5, 30/30.
* @default false
*/
sloppyRanges?: boolean;
}
/**
* Converts date to CronDate
*
* @param d Input date, if using string representation ISO 8001 (2015-11-24T19:40:00) local timezone is expected
* @param tz String representation of target timezone in Europe/Stockholm format, or a number representing offset in minutes.
*/
export declare class CronDate<T = undefined> {
tz: string | number | undefined;
/**
* Current milliseconds
* @type {number}
*/
ms: number;
/**
* Current second (0-59), in local time or target timezone specified by `this.tz`
* @type {number}
*/
second: number;
/**
* Current minute (0-59), in local time or target timezone specified by `this.tz`
* @type {number}
*/
minute: number;
/**
* Current hour (0-23), in local time or target timezone specified by `this.tz`
* @type {number}
*/
hour: number;
/**
* Current day (1-31), in local time or target timezone specified by `this.tz`
* @type {number}
*/
day: number;
/**
* Current month (1-12), in local time or target timezone specified by `this.tz`
* @type {number}
*/
month: number;
/**
* Current full year, in local time or target timezone specified by `this.tz`
*/
year: number;
constructor(d?: CronDate<T> | Date | string | null, tz?: string | number);
/**
* Calculates the last day of a given month.
* Uses a performance optimization for months other than February.
*
* @param year The year
* @param month The month (0-11)
* @returns The last day of the month (1-31)
* @private
*/
private getLastDayOfMonth;
/**
* Calculates the last weekday (Mon-Fri) of a given month.
*
* @param year The target year.
* @param month The target month (0-11).
* @returns The day of the month (1-31) that is the last weekday.
* @private
*/
private getLastWeekday;
/**
* Calculates the nearest weekday (Mon-Fri) to a given day of the month.
* Handles month boundaries.
*
* @param year The target year.
* @param month The target month (0-11).
* @param day The target day (1-31).
* @returns The day of the month (1-31) that is the nearest weekday, or -1 if the day doesn't exist in the month.
*/
private getNearestWeekday;
/**
* Check if the given date is the nth occurrence of a weekday in its month.
*
* @param year The year.
* @param month The month (0 for January, 11 for December).
* @param day The day of the month.
* @param nth The nth occurrence (bitmask).
*
* @return True if the date is the nth occurrence of its weekday, false otherwise.
*/
private isNthWeekdayOfMonth;
/**
* Sets internals using a Date
*/
private fromDate;
/**
* Sets internals by deep copying another CronDate
*
* @param {CronDate} d - Input date
*/
private fromCronDate;
/**
* Reset internal parameters (seconds, minutes, hours) if any of them have exceeded (or could have exceeded) their normal ranges
*
* Will alway return true on february 29th, as that is a date that _could_ be out of bounds
*/
private apply;
/**
* Sets internals by parsing a string
*/
private fromString;
/**
* Find next match of current part
*/
private findNext;
/**
* Internal unified method to find a matching time component in either direction.
* This method searches through the pattern to find the next or previous valid value
* for the specified target component (second, minute, hour, day, or month).
*
* @param options Cron options
* @param target Target property (second, minute, hour, day, month)
* @param pattern Pattern to use
* @param offset Offset to use
* @param direction 1 for forward (next), -1 for backward (previous)
* @returns Status code: 1 = same value matches, 2 = value changed, 3 = no match found
*
* @private
*/
private _findMatch;
/**
* Increment to next run time recursively.
*
* This function traverses the date components (year, month, day, hour, minute, second)
* to find the next date and time that matches the cron pattern. It uses a recursive
* approach to handle the dependencies between different components. For example,
* if the day changes, the hour, minute, and second need to be reset.
*
* The recursion is limited to the year 10000 to prevent potential
* infinite loops or excessive stack depth, and to match the maximum supported
* year in OCPS 1.2 (years 1-9999).
*
* @param pattern The cron pattern used to determine the next run time.
* @param options The cron options that influence the incrementing behavior.
* @param doing The index of the `RecursionSteps` array indicating the current
* date component being processed. 0 represents "month", 1 represents "day", etc.
*
* @returns This `CronDate` instance for chaining, or null if incrementing
* was not possible (e.g., reached year 10000 limit or no matching date).
*
* @private
*/
private recurse;
/**
* Increment to next run time
*
* @param pattern The pattern used to increment the current date.
* @param options Cron options used for incrementing.
* @param hasPreviousRun True if there was a previous run, false otherwise. This is used to determine whether to apply the minimum interval.
* @returns This CronDate instance for chaining, or null if incrementing was not possible (e.g., reached year 3000 limit).
*/
increment(pattern: CronPattern, options: CronOptions<T>, hasPreviousRun: boolean): CronDate<T> | null;
/**
* Decrement to previous run time
*
* @param pattern The pattern used to decrement the current date.
* @param options Cron options used for decrementing.
* @returns This CronDate instance for chaining, or null if decrementing was not possible (e.g., reached year 0).
*/
decrement(pattern: CronPattern, options: CronOptions<T>): CronDate<T> | null;
/**
* Find previous match by recursively checking pattern parts in reverse.
*
* This is the backward equivalent of the recurse() method. It searches backwards
* through time to find the previous date/time that matches the cron pattern.
*
* @param pattern The cron pattern used to determine the previous run time.
* @param options The cron options that influence the decrementing behavior.
* @param doing The index of the `RecursionSteps` array indicating the current
* date component being processed.
*
* @returns This `CronDate` instance for chaining, or null if decrementing
* was not possible (e.g., reached year 0 or no matching date).
*
* @private
*/
private recurseBackward;
/**
* Get the maximum value in a pattern for a given target.
* Used when resetting components during backward recursion.
*
* @param target The target component (second, minute, hour, day, month)
* @param pattern The cron pattern
* @param offset The offset to apply
* @returns The maximum valid value for the target component
*
* @private
*/
private getMaxPatternValue;
/**
* Find previous match for a specific component going backwards in time.
* This is the backward equivalent of the findNext() method.
*
* @param options Cron options
* @param target Target property (second, minute, hour, day, month)
* @param pattern Pattern to use
* @param offset Offset to use
* @returns Status code: 1 = same value matches, 2 = value changed to earlier value, 3 = no match found
*
* @private
*/
private findPrevious;
/**
* Convert current state back to a javascript Date()
*
* @param internal If this is an internal call
*/
getDate(internal?: boolean): Date;
/**
* Convert current state back to a javascript Date() and return UTC milliseconds
*/
getTime(): number;
/**
* Check if the current CronDate matches a cron pattern
*
* @param pattern The cron pattern to match against
* @param options The cron options that influence matching
* @returns true if the date matches the pattern, false otherwise
*/
match(pattern: CronPattern, options: CronOptions<T>): boolean;
}
/**
* An array containing all named cron jobs.
*/
export declare const scheduledJobs: Cron<any>[];
/**
* Callback function type
*
* @param self - Reference to the Cron instance that triggered the callback
* @param context - Optional context value passed through options.context
*
* @returns void or Promise<void> for async callbacks
*/
export type CronCallback<T = undefined> = (self: InstanceType<typeof Cron<T>>, context: T) => void | Promise<void>;
/**
* Cron entrypoint
*
* @constructor
* @param pattern - Input pattern, input date, or input ISO 8601 time string
* @param [fnOrOptions1] - Options or function to be run each iteration of pattern
* @param [fnOrOptions2] - Options or function to be run each iteration of pattern
*/
export declare class Cron<T = undefined> {
name: string | undefined;
options: CronOptions<T>;
private _states;
private fn?;
/**
* Internal helper to get the timezone or UTC offset for date operations.
* Reduces duplication of `this.options.timezone || this.options.utcOffset` throughout the codebase.
*
* @returns The timezone string or UTC offset number
* @private
*/
private getTz;
/**
* Internal helper to apply dayOffset to a date if configured.
* Reduces duplication of dayOffset calculation logic.
*
* @param date - The base date to apply offset to
* @returns The date with dayOffset applied, or the original date if no offset is configured
* @private
*/
private applyDayOffset;
constructor(pattern: string | Date, fnOrOptions1?: CronOptions<T> | CronCallback<T>, fnOrOptions2?: CronOptions<T> | CronCallback<T>);
/**
* Find next runtime, based on supplied date. Strips milliseconds.
*
* @param prev - Optional. Date to start from. Can be a CronDate, Date object, or a string representing a date.
* @returns The next run time as a Date object, or null if there is no next run.
*/
nextRun(prev?: CronDate<T> | Date | string | null): Date | null;
/**
* Find next n runs, based on supplied date. Strips milliseconds.
*
* @param n - Number of runs to enumerate
* @param previous - Date to start from
* @returns - Next n run times
*/
nextRuns(n: number, previous?: Date | string): Date[];
/**
* Find previous n runs, based on supplied date. Strips milliseconds.
*
* @param n - Number of runs to enumerate
* @param reference - Date to start from (defaults to now)
* @returns - Previous n run times in reverse chronological order (most recent first)
*/
previousRuns(n: number, reference?: Date | string): Date[];
/**
* Internal helper to enumerate runs in either direction.
*
* @param n - Number of runs to enumerate
* @param startDate - Date to start from
* @param direction - Direction to enumerate ("next" or "previous")
* @returns Array of run times with dayOffset applied
* @private
*/
private _enumerateRuns;
/**
* Check if a given date matches the cron pattern
*
* @param date - Date to check. Can be a Date object or a string representing a date.
* @returns true if the date matches the pattern, false otherwise
*/
match(date: Date | string): boolean;
/**
* Return the original pattern, if there was one.
* Returns undefined when the job was created with a Date or ISO 8601 string instead of a cron pattern.
*
* @returns Original cron pattern, or undefined for date-based jobs
*/
getPattern(): string | undefined;
/**
* Return the original run-once date, if there was one
*
* @returns Original run-once date, or null if not a run-once job
*/
getOnce(): Date | null;
/**
* Indicates whether or not the cron job is scheduled and running, e.g. awaiting next trigger
*
* @returns Running or not
*/
isRunning(): boolean;
/**
* Indicates whether or not the cron job is permanently stopped
*
* @returns Running or not
*/
isStopped(): boolean;
/**
* Indicates whether or not the cron job is currently working
*
* @returns Running or not
*/
isBusy(): boolean;
/**
* Return current/previous run start time
*
* @returns Current (if running) or previous run time
*/
currentRun(): Date | null;
/**
* Return previous run start time
*
* @returns Previous run time
*/
previousRun(): Date | null;
/**
* Returns number of milliseconds to next run
*
* @param prev Starting date, defaults to now - minimum interval
*/
msToNext(prev?: CronDate<T> | Date | string): number | null;
/**
* Stop execution
*
* Running this will forcefully stop the job, and prevent furter exection. `.resume()` will not work after stopping.
* It will also be removed from the scheduledJobs array if it were named.
*/
stop(): void;
/**
* Pause execution
*
* @returns Wether pause was successful
*/
pause(): boolean;
/**
* Resume execution
*
* @returns Wether resume was successful
*/
resume(): boolean;
/**
* Schedule a new job
*
* @param func - Function to be run each iteration of pattern
*/
schedule(func?: CronCallback<T>): Cron<T>;
/**
* Internal function to trigger a run, used by both scheduled and manual trigger
*/
private _trigger;
/**
* Trigger a run manually
*/
trigger(): Promise<void>;
/**
* Returns number of runs left, undefined = unlimited
*/
runsLeft(): number | undefined;
/**
* Called when it's time to trigger.
* Checks if all conditions are currently met,
* then instantly triggers the scheduled function.
*/
private _checkTrigger;
/**
* Internal version of next. Cron needs millseconds internally, hence _next.
*/
private _next;
/**
* Internal version of previous. Finds the previous scheduled run time.
*
* @param referenceDate - Optional reference date to search backwards from (defaults to now)
* @returns Previous scheduled run time, or null if no previous run exists
*/
private _previous;
/**
* Calculate the previous run if no previous run is supplied, but startAt and interval are set.
* This calculation is only necessary if the startAt time is before the current time.
* Should only be called from the _next function.
*/
private _calculatePreviousRun;
}
export {};