npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

xnode-scheduler

v1.0.8

Published

Simple In-memory job scheduler for Node.js

Downloads

5

Readme

xnode-scheduler

NPM Version NPM Downloads

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 to 2147483646 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 with async: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 takes e: 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/remove
    • fn: Task function definition - can be sync/async function
    • intervalOptions: Interval timer settings. API described below
    • jobOptions: Job Settings. API described below
  • id and status can be accessed directly.

  • status: JobStatus - stores the status of the job, which can be NOT_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 with start command

  • A 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 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

JobOptions

  • async?: boolean - Whether the task is asynchronous
  • errorHandler?: 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 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.