smarttime/ts/smarttime.classes.cronjob.ts

41 lines
1.1 KiB
TypeScript
Raw Normal View History

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-05-27 16:59:26 +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-05-27 16:59:26 +00:00
this.nextExecutionUnix = this.croner.msToNext();
2020-05-25 21:45:43 +00:00
}
if (Date.now() > this.nextExecutionUnix) {
this.jobFunction();
2020-05-27 16:59:26 +00:00
this.nextExecutionUnix = this.croner.msToNext();
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
}
public start() {
this.status = 'started';
}
public stop() {
this.status = 'stopped';
}
2020-05-25 21:49:35 +00:00
}