smarttime/ts/smarttime.classes.cronjob.ts

59 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2022-11-21 08:14:32 +00:00
import * as plugins from './smarttime.plugins.js';
import { CronManager } from './smarttime.classes.cronmanager.js';
2020-05-25 21:45:43 +00:00
2022-11-21 08:14:32 +00:00
import { CronParser } from './smarttime.classes.cronparser.js';
2020-09-07 16:44:54 +00:00
2022-11-21 08:14:32 +00:00
export type TJobFunction =
| ((triggerTimeArg?: number) => void)
| ((triggerTimeArg?: number) => Promise<any>);
2020-05-25 21:45:43 +00:00
export class CronJob {
2022-11-21 10:31:29 +00:00
public cronParser: plugins.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-09-07 23:44:07 +00:00
this.cronParser = plugins.croner(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) {
2022-11-21 00:19:38 +00:00
const maybePromise = this.jobFunction(this.nextExecutionUnix);
2020-09-03 20:06:02 +00:00
if (maybePromise instanceof Promise) {
2022-11-21 08:14:32 +00:00
maybePromise.catch((e) => console.log(e));
2020-09-03 20:06:02 +00:00
}
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() {
2022-11-21 08:14:32 +00:00
return (this.nextExecutionUnix = Date.now() + this.getTimeToNextExecution());
2020-09-04 06:39:22 +00:00
}
/**
* gets the time to next execution
*/
public getTimeToNextExecution() {
2020-09-07 23:44:07 +00:00
return this.cronParser.msToNext();
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
}