smarttime/ts/smarttime.classes.cronjob.ts

52 lines
1.3 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 {
public status: 'started' | 'stopped' | 'initial' = 'initial';
public cronExpression: string;
public jobFunction: TJobFunction;
2020-05-25 21:49:35 +00:00
private cronInterval = plugins.cronParser.parseExpression('* * * * * *');
2020-05-25 21:45:43 +00:00
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;
}
/**
* checks wether the cronjob needs to be executed
*/
public checkExecution() {
if (this.nextExecutionUnix === 0) {
2020-05-25 21:49:35 +00:00
this.nextExecutionUnix = this.cronInterval
.next()
.toDate()
.getTime();
2020-05-25 21:45:43 +00:00
return;
}
if (Date.now() > this.nextExecutionUnix) {
this.jobFunction();
2020-05-25 21:49:35 +00:00
this.nextExecutionUnix = this.cronInterval
.next()
.toDate()
.getTime();
2020-05-25 21:45:43 +00:00
}
}
public start() {
this.cronInterval = this.getCronInterval();
this.status = 'started';
}
public stop() {
this.status = 'stopped';
}
2020-05-25 21:49:35 +00:00
private getCronInterval() {
2020-05-25 21:45:43 +00:00
return plugins.cronParser.parseExpression(this.cronExpression);
}
2020-05-25 21:49:35 +00:00
}