All files / app/services/job-scheduler job-scheduler.service.ts

87.17% Statements 34/39
71.42% Branches 5/7
75% Functions 3/4
87.17% Lines 34/39

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 391x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x     3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x
import { Injectable, isDevMode } from "@angular/core";
 
/**
 * This service runs jobs in the background, 
 * making sure that there are never two jobs running at the same time.
 */
@Injectable({
  providedIn: 'root'
})
export class JobScheduler {
 
  /** Continuosly runs jobs */
  private async startScheduler() {
    if (isDevMode()) console.debug("Running jobs...");
    while (this._jobs.length > 0) {
      try {
        await Promise.all(this._jobs.map(job => job()));
      } catch (e) {
        if (isDevMode()) console.warn("[JobSchedulerService] Job failed", e);
      }
      await new Promise(resolve => setTimeout(resolve, 10));
    }
  }
 
  /** The jobs running */
  private _jobs: (()=>void)[] = [];
 
  /** Adds a job that starts running in the background right away */
  addJob(job: () => void) {
    this._jobs.push(job);
    if (this._jobs.length == 1) this.startScheduler();
  }
 
  /** Removes all jobs */
  stopAllJobs() {
    this._jobs = [];
  }
 
}