All files / src job.ts

100% Statements 18/18
83.33% Branches 5/6
100% Functions 7/7
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 464x 223x           223x 223x       223x 222x   222x         94x 94x 94x 94x         332x 332x 110x 110x   110x             222x 332x        
export class Job<T> {
	private _active = false;
	private _id: NodeJS.Timer | undefined;
	private readonly _interval: number;
	private readonly _job: () => Promise<T>;
 
	public constructor(job: () => Promise<T>, interval: number) {
		this._interval = interval;
		this._job = job;
	}
 
	public async start(): Promise<void> {
		if (!this._active) {
			this._active = true;
 
			return this.run();
		}
	}
 
	public stop(): void {
		Eif (this._active && this._id !== undefined) {
			clearTimeout(this._id);
			this._id = undefined;
			this._active = false;
		}
	}
 
	private async callJobAfterTimeout(): Promise<void> {
		return new Promise<void>(resolve => {
			this._id = setTimeout(async () => {
				await this._job();
				resolve();
 
				return;
			}, this._interval);
		});
	}
 
	private async run(): Promise<void> {
		// tslint:disable-next-line:no-loop-statement
		while (this._active) {
			await this.callJobAfterTimeout();
		}
	}
}