The library provides handling of date ranges with automatic adjustment of the currentDate:
startDate as fallback: If currentDate is not provided but startDate is, the startDate will be used as the currentDate.
const options = { startDate: '2023-01-01T00:00:00Z', // No currentDate provided};// currentDate will be set to 2023-01-01T00:00:00Z automaticallyconst interval = CronExpressionParser.parse('0 0 * * *', options);
Automatic clamping: If currentDate is outside the bounds defined by startDate and endDate, it will be automatically adjusted:
const options = { currentDate: '2022-01-01T00:00:00Z', // Before startDate startDate: '2023-01-01T00:00:00Z', endDate: '2024-01-01T00:00:00Z',};// currentDate will be clamped to startDate (2023-01-01T00:00:00Z)const interval = CronExpressionParser.parse('0 0 * * *', options);
Validation during iteration: While the initial currentDate is automatically adjusted, the library still validates date bounds during iteration:
const options = { currentDate: '2023-12-31T00:00:00Z', endDate: '2024-01-01T00:00:00Z', // Very close end date};const interval = CronExpressionParser.parse('0 0 * * *', options);console.log('Next:', interval.next().toString()); // Works fine// This will throw an error because it would exceed endDatetry { console.log('Next:', interval.next().toString());} catch (err) { console.log('Error:', err.message); // "Out of the time span range"}
This behavior simplifies working with date ranges by removing the need to manually ensure that currentDate is within bounds, reducing confusion and making the API more intuitive.
Crontab File Operations
For working with crontab files, use the CronFileParser:
In several implementations of CRON, it's ambiguous to specify both the Day Of Month and Day Of Week parameters simultaneously, as it's unclear which one should take precedence. Despite this ambiguity, this library allows both parameters to be set by default, although the resultant behavior might not align with your expectations.
To resolve this ambiguity, you can activate the strict mode of the library. When strict mode is enabled, the library enforces several validation rules:
Day Of Month and Day Of Week: Prevents the simultaneous setting of both Day Of Month and Day Of Week fields
Complete Expression: Requires all 6 fields to be present in the expression (second, minute, hour, day of month, month, day of week)
Non-empty Expression: Rejects empty expressions that would otherwise default to '0 * * * * *'
Usable Hashed Range and Step: Rejects a hash the field cannot satisfy - a range reaching outside the field, such as H(0-5) in day of month, or a step wider than the range it applies to, such as H(1-5)/10 (see Hash support)
These validations help ensure that your cron expressions are unambiguous and correctly formatted.
import { CronExpressionParser } from 'cron-parser';// This will throw an error in strict mode because it uses both dayOfMonth and dayOfWeekconst options = { currentDate: new Date('Mon, 12 Sep 2022 14:00:00'), strict: true,};try { // This will throw an error in strict mode CronExpressionParser.parse('0 0 12 1-31 * 1', options);} catch (err) { console.log('Error:', err.message); // Error: Cannot use both dayOfMonth and dayOfWeek together in strict mode!}// This will also throw an error in strict mode because it has fewer than 6 fieldstry { CronExpressionParser.parse('0 20 15 * *', { strict: true });} catch (err) { console.log('Error:', err.message); // Error: Invalid cron expression, expected 6 fields}// This will also throw an error in strict mode because a step of 10 cannot fit the range 1-5try { CronExpressionParser.parse('0 H(1-5)/10 * * * *', { strict: true });} catch (err) { console.log('Error:', err.message); // Error: Invalid step: 10, wider than the 1-5 range of the minute field}
Last Day of Month/Week Support
The library supports parsing the range 0L - 7L in the weekday position of the cron expression, where the L means "last occurrence of this weekday for the month in progress".
For example, the following expression will run on the last Monday of the month at midnight:
import { CronExpressionParser } from 'cron-parser';// Last Monday of every month at midnightconst lastMonday = CronExpressionParser.parse('0 0 0 * * 1L');// You can also combine L expressions with other weekday expressions// This will run every Monday and the last Wednesday of the monthconst mixedWeekdays = CronExpressionParser.parse('0 0 0 * * 1,3L');// Last day of every monthconst lastDay = CronExpressionParser.parse('0 0 L * *');
Using Iterator
import { CronExpressionParser } from 'cron-parser';const interval = CronExpressionParser.parse('0 */2 * * *');// Using for...offor (const date of interval) { console.log('Iterator value:', date.toString()); if (someCondition) break;}// Using take() for a specific number of iterationsconst nextFiveDates = interval.take(5);console.log( 'Next 5 dates:', nextFiveDates.map((date) => date.toString()),);
Timezone Support
The library provides robust timezone support using Luxon, handling DST transitions correctly:
import { CronExpressionParser } from 'cron-parser';const options = { currentDate: '2023-03-26T01:00:00', tz: 'Europe/London',};const interval = CronExpressionParser.parse('0 * * * *', options);// Will correctly handle DST transitionconsole.log('Next dates during DST transition:');console.log(interval.next().toString());console.log(interval.next().toString());console.log(interval.next().toString());
Field Manipulation
You can modify cron fields programmatically using CronFieldCollection.from and construct a new expression:
import { CronExpressionParser, CronFieldCollection, CronHour, CronMinute } from 'cron-parser';// Parse original expressionconst interval = CronExpressionParser.parse('0 7 * * 1-5');// Create new collection with modified fields using raw valuesconst modified = CronFieldCollection.from(interval.fields, { hour: [8], minute: [30], dayOfWeek: [1, 3, 5],});console.log(modified.stringify()); // "30 8 * * 1,3,5"// You can also use CronField instancesconst modified2 = CronFieldCollection.from(interval.fields, { hour: new CronHour([15]), minute: new CronMinute([30]),});console.log(modified2.stringify()); // "30 15 * * 1-5"
The CronFieldCollection.from method accepts either CronField instances or raw values that would be valid for creating new CronField instances. This is particularly useful when you need to modify only specific fields while keeping others unchanged.
Hash support
The library supports adding jitter to the returned intervals using the H special character in a field. When H is specified instead of *, a random value is used (H is replaced by 23, where 23 is picked randomly, within the valid range of the field).
This jitter allows to spread the load when it comes to job scheduling. This feature is inspired by Jenkins's cron syntax.
import { CronExpressionParser } from 'cron-parser';// At 23:<randomized> on every day-of-week from Monday through Friday.const interval = CronExpressionParser.parse('H 23 * * 1-5');// At <randomized>:30 everyday.const interval = CronExpressionParser.parse('30 H * * *');// At every minutes of <randomized> hour at <randomized> second everyday.const interval = CronExpressionParser.parse('H * H * * *');// At every 5th minute starting from a random offset.// For example, if the random offset is 3, it will run at minutes 3, 8, 13, 18, etc.const interval = CronExpressionParser.parse('H/5 * * * *');// At a random minute within the range 0-10 everyday.const interval = CronExpressionParser.parse('H(0-10) * * * *');// At every 5th minute starting from a random offset within the range 0-4.// For example, if the random offset is 2, it will run at minutes 2, 7, 12, 17, etc.// The random offset is constrained to be less than the step value.const interval = CronExpressionParser.parse('H(0-29)/5 * * * *');// At every minute of the third <randomized> day of the monthconst interval = CronExpressionParser.parse('* * * * H#3');
A step only produces several occurrences while it is narrow enough to fit the range more than once. When the step is wider than the range - as in H(1-5)/10, or H/60 in a field whose constraints are narrower than 60 - no step-aligned value is guaranteed to land inside the range, so the field falls back to a single random occurrence within it, exactly as H(1-5) would give:
import { CronExpressionParser } from 'cron-parser';// A step of 10 cannot fit the range 1-5, so this behaves like 'H(1-5)':// one random minute between 1 and 5.const interval = CronExpressionParser.parse('H(1-5)/10 * * * *');
A range is first narrowed to what the field can hold, so H(0-5) in day of month picks a day between 1 and 5, and H(50-100)/60 in the minute field steps across 50-59 rather than the 50-100 that was written. A range with nothing left after narrowing, such as H(0-0)/40 in day of month, is rejected.
Whether such an expression is a mistake is up to you: enable strict mode to have it rejected instead of falling back.
The randomness is seed-able using the hashSeed option of CronExpressionOptions:
import { CronExpressionParser } from 'cron-parser';const options = { currentDate: '2023-03-26T01:00:00', hashSeed: 'main-backup', // Generally, hashSeed would be a job name for example};const interval = CronExpressionParser.parse('H * * * H', options);console.log(interval.stringify()); // "12 * * * 4"const otherInterval = CronExpressionParser.parse('H * * * H', options);// Using the same seed will always return the same jitterconsole.log(otherInterval.stringify()); // "12 * * * 4"
Contributing
We welcome contributions! Please see our Contributing Guide for details on: