smarttime/ts/smarttime.classes.cronjob.ts

57 lines
1.5 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-09-07 16:44:54 +00:00
import { CronParser } from './smarttime.classes.cronparser';
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-09-07 16:44:54 +00:00
public cronParser: CronParser;
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-09-07 16:44:54 +00:00
this.cronParser = new CronParser(cronExpressionArg);
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() {
2020-09-07 16:44:54 +00:00
return this.cronParser.getMsToNextTimeMatch();
2020-09-04 06:39:22 +00:00
}
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
}