croner
Version:
Trigger functions and/or evaluate cron expressions in JavaScript. No dependencies. Most features. All environments.
437 lines (434 loc) • 13.2 kB
TypeScript
// Generated by dts-bundle-generator v9.5.1
export type CatchCallbackFn = (e: unknown, job: Cron) => void;
export type ProtectCallbackFn = (job: Cron) => void;
/**
* Options for configuring cron jobs.
*
* @interface
*/
export interface CronOptions {
/**
* 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;
/**
* The date and time at which the job should stop running.
*/
stopAt?: string | Date | CronDate;
/**
* The timezone for the cron job.
*/
timezone?: string;
/**
* The UTC offset for the cron job, in minutes.
*/
utcOffset?: number;
/**
* If true, enables legacy mode for compatibility with older cron implementations.
* @default true
*/
legacyMode?: boolean;
/**
* An optional context object that will be passed to the job function.
*/
context?: unknown;
}
/**
* Create a CronPattern instance from pattern string ('* * * * * *')
* @constructor
* @param {string} pattern - Input pattern
* @param {string} timezone - Input timezone, used for '?'-substitution
*/
export declare class CronPattern {
pattern: string;
timezone?: string;
second: number[];
minute: number[];
hour: number[];
day: number[];
month: number[];
dayOfWeek: number[];
lastDayOfMonth: boolean;
starDOM: boolean;
starDOW: boolean;
constructor(pattern: string, timezone?: string);
/**
* 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 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;
/**
* 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 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;
}
/**
* 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 {
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 | Date | string | null, tz?: string | number);
/**
* 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;
/**
* 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 currently limited to the year 3000 to prevent potential
* infinite loops or excessive stack depth. If you need to schedule beyond
* the year 3000, please open an issue on GitHub to discuss possible solutions.
*
* @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 3000 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, hasPreviousRun: boolean): CronDate | null;
/**
* 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;
}
/**
* An array containing all named cron jobs.
*/
export declare const scheduledJobs: Cron[];
/**
* 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 {
name: string | undefined;
options: CronOptions;
private _states;
private fn?;
constructor(pattern: string | Date, fnOrOptions1?: CronOptions | Function, fnOrOptions2?: CronOptions | Function);
/**
* 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 | 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[];
/**
* Return the original pattern, if there was one
*
* @returns Original pattern
*/
getPattern(): string | undefined;
/**
* 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 | 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?: Function): Cron;
/**
* 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;
/**
* 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 {};