Natural Cron ⏰⏰ - Create cron expressions with human readable APIs
Tags: javascript, cronjobs, scheduling, node
Published: 2023-11-07 03:03:57

## Natural Cron ⏰⏰

Natural Cron is an easy-to-use Node.js library that simplifies the creation and validation of cron expressions with human-readable APIs. It's designed to make working with cron jobs in your Node.js applications more intuitive and efficient. In this article, we'll explore the features of Natural Cron and provide examples of how you can use it to create custom cron expressions for various scheduling scenarios.

## Features

Natural Cron offers a range of features to help you work with cron expressions effectively:

1. **Chainable Methods:** Constructing complex cron expressions is made easy with chainable methods that allow you to specify minute, hour, day of the month, month, and day of the week.

2. **Validation:** Natural Cron provides validation for each component of a cron expression, ensuring that your expressions are valid. If you provide invalid input, it will generate helpful error messages.

3. **TypeScript Support:** For those who value strong typing and intelligent code completion, Natural Cron offers TypeScript support.

Now, let's dive into how you can install and use Natural Cron in your Node.js projects.

## Installation

You can install Natural Cron using npm or yarn. Here's how to do it:

Using npm:
```bash
npm install natural-cron
```

Using yarn:
```bash
yarn add natural-cron
```

## Usage

Natural Cron provides an intuitive API for creating custom cron expressions. Let's explore some common scheduling scenarios and how you can use the library to generate the corresponding cron expressions.

```javascript
const { CronExpressionBuilder, CronValidators } = require('natural-cron');
const schedule = new CronExpressionBuilder();
```

### Examples

Here are several examples of scheduling scenarios and the corresponding Natural Cron expressions:

**Run a job at 5:30 PM every day:**

 ```javascript
 schedule
  .atTime('17:30')
  .compile(); // Generates: 30 17 * * *
 ```

**Run at 9 AM on weekdays (Monday to Friday):**
 ```javascript
 schedule
  .atTime('09:00')
  .onWeekDays([1, 2, 3, 4, 5])
  .compile(); // Generates: 0 9 * * 1-5
 ```

**Run at noon on the 1st and 15th of the month:**
```javascript
 schedule
  .atTime('12:00')
  .onDaysOfMonth([1, 15])
  .compile(); // Generates: 0 12 1,15 * *
```


**Run at midnight during January and July:**
```javascript
 schedule
  .atTime('00:00')
  .duringMonths([1, 7])
  .compile(); // Generates: 0 0 * 1,7 *
```

**Run every 15 minutes:**
```javascript
 schedule
  .everyX(15, CronTimeUnit.Minute)
  .compile(); // Generates: */15 * * * *
```

**Run every day at noon:**
```javascript
 schedule
  .every('day')
  .atHours([12])
  .compile(); // Generates: 0 12 * * *
```

**Run every Sunday at 5 PM:**
```javascript
 schedule
  .onWeekDays([0])
  .atHours([17])
  .compile(); // Generates: 0 17 * * 0
```

**Run the 1st day of every month at 1 AM:**
```javascript
 schedule
  .onDaysOfMonth([1])
  .every('month')
  .atHours([1])
  .compile(); // Generates: 0 1 1 * *
```

**Run every weekday at 8:30 AM:**
```javascript
 schedule
  .atTime('08:30')
  .onWeekDays([1, 2, 3, 4, 5])
  .compile(); // Generates: 30 8 * * 1-5
```

**Run every 6 hours:**
```javascript
 schedule
  .everyX(6, CronTimeUnit.Hour)
  .compile(); // Generates: 0 */6 * * *
```

**Run every quarter at midnight:**
```javascript
 schedule
  .duringMonths([1, 4, 7, 10])
  .onDaysOfMonth([1])
  .atTime('00:00')
  .compile(); // Generates: 0 0 1 1,4,7,10 *
```

**Run every Saturday and Sunday at 10:15 AM:**
```javascript
 schedule
  .atTime('10:15')
  .onWeekDays([6, 0])
  .compile(); // Generates: 15 10 * * 6,0
```

**Run at 9 AM, 12 PM, and 3 PM every day:**
```javascript
 schedule
  .every('day')
  .atHours([9, 12, 15])
  .compile(); // Generates: 0 9,12,15 * * *
```

**Run at 7 AM, 2 PM, and 10 PM on Tuesdays:**
```javascript
 schedule
  .atHours([7, 14, 22])
  .onWeekDays([2])
  .compile(); // Generates: 0 7,14,22 * * 2
```

**Run at 20 past every hour on the 5th of July:**
```javascript 
 schedule
  .atMinutes([20])
  .onDaysOfMonth([5])
  .duringMonths([7])
  .compile(); // Generates: 20 * 5 7 *
```

**Run every 5 minutes during office hours - using `every()`:**
```javascript
 schedule
  .every('minute')
  .atMinutes([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55])
  .atHours([9, 10, 11, 12, 13, 14, 15, 16])
  .compile(); 
  // Generates: 0,5,10,15,20,25,30,35,40,45,50,55 9-16 * * *
```

**Run every 5 minutes during office hours - using `everyX()`:**
```javascript
 schedule
 .everyX(5, CronTimeUnit.Minute)
 .atHours([9, 10, 11, 12, 13, 14, 15, 16])
 .compile(); // Generates: */5 9-16 * * *
```

**Run at quarter past and quarter to every hour:**
```javascript
 schedule
  .every('hour')
  .atMinutes([15, 45])
  .compile(); // Generates: 15,45 * * * *
```

> Please note that the **schedule** object is an instance of **CronExpressionBuilder** used for generating the cron expressions.


### API Reference

#### `CronExpressionBuilder`

- `atMinutes(minutes: Array<number>): this`
- `atHours(hours: Array<number>): this`
- `atTime(time: string): this`
- `every(unit: string): this`
- `everyX(interval: number, unit: ScheduleUnit): this`
- `onWeekdays(days: Array<number>): this`
- `onDaysOfMonth(days: Array<number>): this`
- `duringMonths(months: Array<number>): this`
- `compile(): string` - Get the cron expression

#### `CronValidators`

Static methods for validating cron expression components:

- `validateMinute(minute: number)`
- `validateHour(hour: number)`
- `validateDayOfMonth(day: number)`
- `validateMonth(month: number)`
- `validateDayOfWeek(day: number)`


- `validateTime(time: string)`

#### `CronTimeUnit`

Use the `CronTimeUnit` enum for `ScheduleUnit`:

```javascript
export enum CronTimeUnit {
  Minute = 'minute',
  Hour = 'hour',
  DayOfMonth = 'dayOfMonth',
  Month = 'month',
  DayOfWeek = 'dayOfWeek',
}
```

Natural Cron simplifies the process of working with cron expressions, making it easier to schedule tasks in your Node.js applications. Whether you need to create a simple daily job or a complex, customized schedule, Natural Cron has you covered. With its human-readable API and validation features, it's a powerful tool for managing cron jobs with confidence.

Give Natural Cron a try in your Node.js projects and enjoy a more natural way to work with cron expressions!