@nivinjoseph/n-job
v2.0.4
Published
Job scheduling and execution
Readme
n-job
A powerful and flexible job scheduling and execution library for Node.js applications.
Features
- Two types of jobs:
- Scheduled Jobs: Execute at specific times or on specific schedules (e.g., every Monday at 9 AM)
- Timed Jobs: Execute repeatedly at fixed intervals (e.g., every 5 minutes)
- Support for timezone-aware scheduling
- Job management and monitoring capabilities
- TypeScript support
- Built with modern Node.js features
Installation
npm install @nivinjoseph/n-job
# or
yarn add @nivinjoseph/n-jobRequirements
- Node.js >= 20.10
- TypeScript (optional, but recommended)
Usage
Basic Setup
import { JobManager, Schedule, ScheduleDateTimeZone, ScheduledJob, TimedJob } from "@nivinjoseph/n-job";
import { inject } from "@nivinjoseph/n-ject";
import type { Logger } from "@nivinjoseph/n-log";
// Create a job manager instance
const jobManager = new JobManager();
// Define a timed job
@inject("Logger")
export class TimedTestJob extends TimedJob
{
public constructor(logger: Logger)
{
super(logger, Duration.fromMinutes(10) as any);
}
protected async run(): Promise<void>
{
await this.logger.logInfo("This is a test timed job running every 10 minutes");
}
}
// Register and start jobs
jobManager.registerJobs(TimedTestJob);
jobManager.bootstrap();
jobManager.beginJobs();Schedule Configuration
The Schedule class allows you to create flexible schedules for your jobs. You can combine different time components to create the exact schedule you need.
Time Components
You can set the following time components in any order:
const schedule = new Schedule()
.setTimeZone(ScheduleDateTimeZone.utc) // Set timezone
.setMonth(12) // December (1-12)
.setDayOfMonth(31) // 31st day of month (1-31)
.setDayOfWeek(1) // Monday (1-7, where 1 is Monday)
.setHour(14) // 2 PM (0-23)
.setMinute(30); // 30 minutes (0-59)Schedule Patterns
Daily Schedule
// Run every day at 2:30 PM UTC const dailySchedule = new Schedule() .setTimeZone(ScheduleDateTimeZone.utc) .setHour(14) .setMinute(30);Weekly Schedule
// Run every Monday at 9:00 AM PST const weeklySchedule = new Schedule() .setTimeZone(ScheduleDateTimeZone.pst) .setDayOfWeek(1) // 1 = Monday .setHour(9) .setMinute(0);Monthly Schedule
// Run on the 1st of every month at midnight EST const monthlySchedule = new Schedule() .setTimeZone(ScheduleDateTimeZone.est) .setDayOfMonth(1) .setHour(0) .setMinute(0);Specific Date and Time
// Run on December 31st at 11:59 PM UTC const specificSchedule = new Schedule() .setTimeZone(ScheduleDateTimeZone.utc) .setMonth(12) .setDayOfMonth(31) .setHour(23) .setMinute(59);
Important Notes
Recurring Schedules:
- If you don't set
monthanddayOfMonth, the schedule will repeat at the specified time every day - If you set
dayOfWeekbut notmonthanddayOfMonth, it will repeat weekly - If you set
monthanddayOfMonth, it will repeat yearly
- If you don't set
Time Components:
dayOfWeekanddayOfMonthare mutually exclusive - you can't set both- All time components are optional except
hourandminute - If you don't set
timeZone, it defaults to the local timezone
Validation:
- The library validates that the day of month exists for the specified month
- For February 29th, it handles leap years automatically
Scheduled Jobs
Scheduled jobs execute at specific times or on specific schedules. They use the Schedule class to define when they should run.
Example: Daily Report Job
import { inject } from "@nivinjoseph/n-ject";
import { Schedule, ScheduleDateTimeZone, ScheduledJob } from "@nivinjoseph/n-job";
import type { Logger } from "@nivinjoseph/n-log";
@inject("Logger")
export class DailyReportJob extends ScheduledJob
{
public constructor(logger: Logger)
{
super(logger, new Schedule()
.setTimeZone(ScheduleDateTimeZone.utc)
.setHour(8) // 8 AM
.setMinute(0) // 00 minutes
);
}
protected async run(): Promise<void>
{
await this.logger.logInfo("Generating daily report...");
// Add your report generation logic here
}
}
// Register the job with the job manager
jobManager.registerJobs(DailyReportJob);Job Management
// Register multiple jobs
jobManager.registerJobs(TimedTestJob, DailyReportJob);
// Bootstrap the job manager
jobManager.bootstrap();
// Start all registered jobs
jobManager.beginJobs();
// Clean up when done
await jobManager.dispose();API Reference
JobManager
The main class for managing jobs and schedules.
Constructor
JobManager(container?: Container)- Optional container for dependency injection
Properties
containerRegistry: Registry- Access to the container registryserviceLocator: ServiceLocator- Access to the service locator
Methods
useInstaller(installer: ComponentInstaller): this- Add a component installerregisterJobs(...jobClasses: ReadonlyArray<ClassHierarchy<Job>>): this- Register job classesbootstrap(): void- Initialize the job manager and resolve dependenciesbeginJobs(): Promise<void>- Start all registered jobsdispose(): Promise<void>- Clean up resources
Schedule
Class for creating job schedules.
Methods
setTimeZone(value: ScheduleDateTimeZone): thissetMinute(value: number): this- [0-59]setHour(value: number): this- [0-23]setDayOfWeek(value: number): this- [1-7] where 1 is Monday and 7 is SundaysetDayOfMonth(value: number): this- [1-31]setMonth(value: number): this- [1-12]
ScheduleDateTimeZone
Enum for supported timezones:
utclocalest(Eastern Time)pst(Pacific Time)
ScheduledJob
Base class for scheduled jobs.
Constructor
ScheduledJob(logger: Logger, schedule: Schedule)
Methods
protected run(): Promise<void>- Override this method to implement job logic
TimedJob
Base class for timed jobs.
Constructor
TimedJob(logger: Logger, intervalInMs: number)
Methods
protected run(): Promise<void>- Override this method to implement job logic
Error Handling
The library provides custom exceptions for handling scheduling errors:
import { InvalidScheduleException } from "@nivinjoseph/n-job";
try {
// Schedule job
} catch (error) {
if (error instanceof InvalidScheduleException) {
// Handle invalid schedule
}
}Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
