1.0.1 • Published 3 years ago

x-node-job-scheduler v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

x-node-job-scheduler

NPM Version NPM Downloads

Simple In-memory Node.js job scheduling library to execute specified tasks within fixed intervals of time (e.g. "each x seconds")

Created in Typescript

Sept 2021 This library is under active development and being properly tested at the moment. It is expected to complete very soon

Getting started

Installation:

npm i x-node-job-scheduler

Usage Example:

const {JobAsync, JobSync, Scheduler, JobStatus} = require('x-node-job-scheduler')

// Create Scheduler instance
const scheduler = new Scheduler();

// Define job and errorHandler(optional)
const fn = function() { counter++}
const errorHandler = function(error){ console.log(error.message )}

// Create Jobs
const j1 = new JobSync(fn, {seconds: 30, minutes: 1})
const j2 = new JobSync(fn, {hours: 2}, 'jobId2', errorHandler, false);

// Add Jobs to scheduler
scheduler.addJob(j1);
scheduler.addJob(j2);

// Stop a particular job
scheduler.stopJob(j1.id);

// Job Statuses mapped to JobStatus Enum
assert(j1.status === JobStatus.STOPPED);

// Individual Jobs can also be stopped directly through Job instance
j2.stop();

// Scheduler Status
scheduler.status();

// Stop All running jobs
scheduler.stop()

Usage with async tasks - JobAsync

For asyncronous Jobs, we need to use class JobAsync while creating Job instance. Using sync task(fn) within JobAsync might lead to unhandled rejections.

const {JobAsync, JobSync, Scheduler, JobStatus} = require('x-node-job-scheduler')

// Create Scheduler instance
const scheduler = new Scheduler();

// Define async job and errorHandler(optional)
let counter = 0;
const asyncFn = function() { return someAsyncCall().then(result=> 'continue chain') }
const errorHandler = function(error){ console.log(error.message )}

// Create async Job
const jAsync = new JobAsync(fn, {seconds: 10}, undefined, errorHandler);

// Add Job to scheduler
scheduler.addJob(jAsync);

// Stop All running jobs
scheduler.stop()

Note that in order to avoid memory leaks due to calling contexts, it is highly recommended to use promise chaining instead of async/await within JobAsync fn definition.

Error Handling

For both JobSync and JobAsync we can provide a custom error handler function with 1 param - (error: Error). This is optional and if not provided (or falsy), default error handler prints the error to console.

Note : For JobAsync , we should not provide a seperate .catch() block within the task definition. Contents of catch function must be written in the form of Error handler of JobAsync class

API for TimerOptions

  • days?: number - how many days to wait before executing the job for the next time;
  • hours?: number - how many hours to wait before executing the job for the next time;
  • minutes?: number - how many minutes to wait before executing the job for the next time;
  • seconds?: number - how many seconds to wait before executing the job for the next time;
  • milliseconds?: number - how many milliseconds to wait before executing the job for the next time;

API for JobSync and JobAsync

  • constructor(fn, t: TimerOptions, id: string, errorHandler, runAtStart: boolean ) : fn: JobAsync or JobSync instance which denotes the task. runAtStart represents that a job should also run immediately once it is started (or added to scheduler). Default runAtStart = true

  • id: string - A property to access Job ID. If not provided while creation, default value is generated by UUID.

  • start(): void - starts, or restarts (if it's already running) the job;
  • stop(): void - stops the job. Can be restarted again with start command
  • JobStatus - An Enum which can be either of: NOT_STARTED, RUNNING, STOPPED. This should be used for easily accessing and validating Job status
  • status: JobStatus - stores the status of the job

API for Scheduler

  • addJob(j: JobSync | JobAsync) : void - Add Job by ID within scheduler and Start it.
  • getJob(id: string): JobSync | JobAsync - Get Job by ID. For invalid IDs , error is thrown
  • startJob(id: string): void - Start a Job by ID. For invalid IDs, error is thrown
  • stopJob(id: string): void - Start a Job by ID. For invalid IDs, error is thrown
  • removeJob(id: string) - Stops the given job and removes it from scheduler. For invalid IDs , No error is thrown.
  • stop(): void - Stop all jobs in scheduler
  • status() - Returns a POJO representing various metrics related to current statuses of all jobs.
1.0.1

3 years ago

1.0.0

3 years ago