run cron at full hours

closes #20
This commit is contained in:
HF 2022-07-11 10:42:50 +02:00
parent d7debd2614
commit 2c4b856f74

View File

@ -1,37 +1,47 @@
/* /*
* Cron job of argumentless functions that will get run in a specific interval, * Cron job of argumentless functions that will get run in a specific interval,
* per default just one will get created which runs daily, * at full hours
* hook it up to some timer function that causes the least load
* @flow
*/ */
import { HOUR } from '../core/constants'; import { HOUR } from '../core/constants';
import logger from '../core/logger'; import logger from '../core/logger';
class Cron { class Cron {
lastRun: number; // timestamp of last run
interval: number; lastRun;
functions: Array; // interval in hours
interval;
// array with functions to run
functions;
// timeout return
timeout; timeout;
// interval = how many hours between runs // interval = how many hours between runs
// lastRun = when this cron job was last run // lastRun = when this cron job was last run
constructor(interval: number, lastRun: number = 0) { constructor(interval, lastRun = 0) {
this.checkForExecution = this.checkForExecution.bind(this); this.checkForExecution = this.checkForExecution.bind(this);
this.interval = interval; this.interval = interval;
this.lastRun = lastRun; this.lastRun = lastRun;
this.functions = []; this.functions = [];
this.timeout = setInterval(this.checkForExecution, HOUR); const ct = new Date();
const msToNextFullHour = 3600000
- (ct.getUTCMinutes() * 60 + ct.getUTCSeconds()) * 1000;
this.timeout = setTimeout(this.checkForExecution, msToNextFullHour);
} }
checkForExecution() { checkForExecution() {
const curTime = Date.now(); const curTime = Date.now();
if (curTime > this.lastRun + this.interval * HOUR) { this.timeout = setTimeout(this.checkForExecution, HOUR);
if (curTime + 10000 > this.lastRun + this.interval * HOUR) {
logger.info(`Run cron events for interval: ${this.interval}h`); logger.info(`Run cron events for interval: ${this.interval}h`);
this.lastRun = curTime; this.lastRun = curTime;
this.functions.forEach(async (item) => { this.functions.forEach(async (item) => {
item(); try {
item();
} catch (err) {
logger.error(`Error on cron job: ${err.message}`);
}
}); });
} }
} }
@ -45,7 +55,9 @@ class Cron {
function initializeDailyCron() { function initializeDailyCron() {
const now = new Date(); const now = new Date();
// make it first run at midnight // make it first run at midnight
const lastRun = now.getTime() - now.getHours() * HOUR; const lastRun = now.getTime()
- now.getUTCHours() * HOUR
- (now.getUTCMinutes() * 60 - now.getUTCSeconds()) * 1000;
const cron = new Cron(24, lastRun); const cron = new Cron(24, lastRun);
return cron; return cron;
} }