async-interval-job
Version:
setInterval for promises and async functions. Support graceful shutdown and prevent multiple executions from overlapping in time.
91 lines (85 loc) • 3.02 kB
TypeScript
import { Timer } from 'nodejs-timer';
/*!
* async-interval-job
* Home page: https://github.com/a179346/async-interval-job
* npm: https://www.npmjs.com/package/async-interval-job
*/
/** =================== USAGE ==================
import { AsyncIntervalJob } from 'async-interval-job';
const job = new AsyncIntervalJob(async () => {
// Execute for each interval.
}, 60 * 1000);
job.start();
async function gracefulShutdown() {
await job.stop();
// Can close the db connections here ...
}
=============================================== */
export interface AsyncIntervalJobOptions {
/**
* If true, Auto start interval job after constructor. Otherwise, `job.start()` should be called to start the job.
* default: false
*/
autoStart?: boolean;
/**
* If true, Start first handling when job start. Otherwise, Start first handling at `intervalMs` after job start.
* default: false
*/
runImmediately?: boolean;
/**
* If true, Job will be stopped when error occurred during handling, and won't exexcute next handling.
* default: false
*/
stopOnError?: boolean;
}
export declare type AsyncIntervalJobHandler = () => void | Promise<void>;
export interface AsyncIntervalJobState {
/**
* True if the input handler is executing.
*/
isHandling: boolean;
/**
* True if the job is at the interval between handler execution.
*/
isWaitForNextHandle: boolean;
/**
* job.stop was called, and is now waiting for the handler execution finish.
*/
isBeforeStop: boolean;
}
export declare class AsyncIntervalJob {
/**
* Construtor of AsyncIntervalJob
* @param handler `MUST` Function to execute for each interval.
* @param intervalMs `MUST` Millisecond to wait between each function execution.
* @param options {AsyncIntervalJobOptions} `OPTIONAL`
*/
constructor(handler: AsyncIntervalJobHandler, intervalMs: number, options?: AsyncIntervalJobOptions);
/**
* Start the Job
*/
start(): void;
/**
* Stop the job.
* @returns Promise -
* If job isn't handling, will clear the interval and resolve the returned promise.
* Otherwise, will wait until the handling finish and resolve the returned promise.
*/
stop(): Promise<void>;
/**
* Get current state of the interval job
* @returns {AsyncIntervalJobState}
*/
getState(): AsyncIntervalJobState;
protected readonly _timer: Timer<[]>;
protected readonly _handler: AsyncIntervalJobHandler;
protected readonly _intervalMs: number;
protected readonly _options: Required<AsyncIntervalJobOptions>;
protected _isHandling: boolean;
protected get _isWaitForNextHandle(): boolean;
protected get _isLooping(): boolean;
protected _isBeforeStop: boolean;
protected readonly _stopCallbacks: (() => void)[];
protected _loop(): Promise<void>;
protected _run(): Promise<void>;
}