2020-05-25 21:45:43 +00:00
|
|
|
import * as plugins from './smarttime.plugins';
|
|
|
|
import { CronManager } from './smarttime.classes.cronmanager';
|
|
|
|
|
2020-05-25 21:49:35 +00:00
|
|
|
export type TJobFunction = (() => void) | (() => Promise<any>);
|
2020-05-25 21:45:43 +00:00
|
|
|
|
|
|
|
export class CronJob {
|
2020-07-11 21:41:33 +00:00
|
|
|
public croner;
|
2020-05-25 21:45:43 +00:00
|
|
|
public status: 'started' | 'stopped' | 'initial' = 'initial';
|
|
|
|
public cronExpression: string;
|
|
|
|
public jobFunction: TJobFunction;
|
|
|
|
private nextExecutionUnix: number = 0;
|
|
|
|
|
2020-05-25 21:49:35 +00:00
|
|
|
constructor(cronManager: CronManager, cronExpressionArg: string, jobFunction: TJobFunction) {
|
2020-05-25 21:45:43 +00:00
|
|
|
this.cronExpression = cronExpressionArg;
|
|
|
|
this.jobFunction = jobFunction;
|
2020-05-27 16:59:26 +00:00
|
|
|
this.croner = plugins.croner(this.cronExpression);
|
2020-05-25 21:45:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* checks wether the cronjob needs to be executed
|
|
|
|
*/
|
2020-05-27 16:59:26 +00:00
|
|
|
public checkExecution(): number {
|
2020-05-25 21:45:43 +00:00
|
|
|
if (this.nextExecutionUnix === 0) {
|
2020-09-04 06:39:22 +00:00
|
|
|
this.getNextExecutionTime();
|
2020-05-25 21:45:43 +00:00
|
|
|
}
|
|
|
|
if (Date.now() > this.nextExecutionUnix) {
|
2020-09-03 20:06:02 +00:00
|
|
|
const maybePromise = this.jobFunction();
|
|
|
|
if (maybePromise instanceof Promise) {
|
|
|
|
maybePromise.catch(e => console.log(e));
|
|
|
|
}
|
2020-09-04 06:39:22 +00:00
|
|
|
this.nextExecutionUnix = this.getNextExecutionTime();
|
2020-05-25 21:45:43 +00:00
|
|
|
}
|
2020-05-27 16:59:26 +00:00
|
|
|
return this.nextExecutionUnix;
|
2020-05-25 21:45:43 +00:00
|
|
|
}
|
|
|
|
|
2020-09-04 06:39:22 +00:00
|
|
|
public getNextExecutionTime() {
|
|
|
|
return this.nextExecutionUnix = Date.now() + this.getTimeToNextExecution();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* gets the time to next execution
|
|
|
|
*/
|
|
|
|
public getTimeToNextExecution() {
|
|
|
|
return this.croner.msToNext();
|
|
|
|
}
|
|
|
|
|
2020-05-25 21:45:43 +00:00
|
|
|
public start() {
|
|
|
|
this.status = 'started';
|
|
|
|
}
|
|
|
|
|
|
|
|
public stop() {
|
|
|
|
this.status = 'stopped';
|
|
|
|
}
|
2020-05-25 21:49:35 +00:00
|
|
|
}
|