xnode-scheduler
v1.0.8
Published
Simple In-memory job scheduler for Node.js
Downloads
5
Maintainers
Readme
xnode-scheduler
Simple In-memory Node.js job scheduler library to execute tasks within fixed intervals
- Useful to run sync/async(promise based) jobs every fixed interval with delay 'x'. Uses NodeJS SetInterval under the wraps.
- Not suitable to run cron expressions yet
- Supports
milliseconds
,seconds
,minutes
,hours
,days
as inputs. Range of delays supported :1 millisecond
to2147483646 milliseconds
- Created in Typescript.
- No dependency on any external package
- Does not support caching
- Created for NodeJS. Not yet tested for browsers.
Getting started
Installation:
npm i xnode-scheduler
Usage Example:
const { JobStatus, IntervalBasedJob, XnodeScheduler } = require('../dist/index');
// Create Scheduler instance
const scheduler = new XnodeScheduler();
// Define job and errorHandler(optional)
const fn = function() { counter++}
const errorHandler = function(error){ console.log(error.message )}
// Create Jobs
const j1 = new IntervalBasedJob('j1', fn, { seconds: 1 });
const j2 = new IntervalBasedJob('j2', fn, { hours: 2 }, {
async: true,
errorHandler: (error)=>{console.log(error)},
runImmediately: true
});
// Add Jobs to scheduler
scheduler.addJob(j1);
scheduler.addJob(j2);
scheduler.removeJob('jn'); // Removes and stops the job
scheduler.getJob('jx') // throws error for non existent Job ID
const test = scheduler.getJob('j1');
assert(test instanceof IntervalBasedJob);
// Stop a particular job
scheduler.stopJob('j1');
// 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()
Notes for Usage
- For asyncronous Jobs, we need to provide
async : true
within JobOptions. Using sync tasks withasync:true
might lead to unhandled rejections. - This library does not do throttling or caching.
- Firing too many async Jobs in a short interval might lead to queuing up requests - leading to low performance. Delays should be used with caution.
- For Async Jobs, it is highly recommended to use promise chaining instead of async/await pattern within function definition. This is to avoid memory leaks due to calling contexts.
Error Handling
- For both sync/async,
JobOptions
has errorHandler function which takese: Error
parameter. - This is optional and if not provided (or falsy), default error handler will print the Job ID + error message to console.
- For Async Jobs, the error handler function is appended to the function chain as a
.catch()
block at the end.
API Documentation
IntervalBasedJob
constructor(id: string, fn, intervalOptions: IntervalOptions, jobOptions: JobOptions)
id
: Unique Job ID to be used to Query Jobs and stop/removefn
: Task function definition - can be sync/async functionintervalOptions
: Interval timer settings. API described belowjobOptions
: Job Settings. API described below
id
andstatus
can be accessed directly.status: JobStatus
- stores the status of the job, which can beNOT_STARTED
,RUNNING
,STOPPED
.JobStatus
enum can be used to validate status at any state.start(): void
- starts, or restarts (if it's already running) the job;stop(): void
- stops the job. Can be restarted again withstart
commandA Job can be started and stopped any number of times.
IntervalOptions
days?: number
- how many days to wait before executing the job for the next timehours?: number
- how many hours to wait before executing the job for the next timeminutes?: number
- how many minutes to wait before executing the job for the next timeseconds?: number
- how many seconds to wait before executing the job for the next timemilliseconds?: number
- how many milliseconds to wait before executing the job for the next time
JobOptions
async?: boolean
- Whether the task is asynchronouserrorHandler?: Fn(e:Error)
- Error handler for each invocation. Optional - By default - it prints Job ID and error message to console.runImmediately?: boolean
- If true, Job's first run will be immediately when started. By default - it is undefined.
XnodeScheduler
- A scheduler instance can have only 1 job by a unique name.
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 thrownstartJob(id: string): void
- Start a Job by ID. For invalid IDs, error is thrownstopJob(id: string): void
- Start a Job by ID. For invalid IDs, error is thrownremoveJob(id: string)
- Stops the given job and removes it from scheduler. For invalid IDs , No error is thrown.stop(): void
- Stop all jobs in schedulerstatus()
- Returns a POJO representing various metrics related to current statuses of all jobs.