diff --git a/src/utils/cron.js b/src/utils/cron.js index fe40856..b4b76fa 100644 --- a/src/utils/cron.js +++ b/src/utils/cron.js @@ -1,37 +1,47 @@ /* * Cron job of argumentless functions that will get run in a specific interval, - * per default just one will get created which runs daily, - * hook it up to some timer function that causes the least load - * @flow + * at full hours */ import { HOUR } from '../core/constants'; import logger from '../core/logger'; class Cron { - lastRun: number; - interval: number; - functions: Array; + // timestamp of last run + lastRun; + // interval in hours + interval; + // array with functions to run + functions; + // timeout return timeout; // interval = how many hours between runs // 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.interval = interval; this.lastRun = lastRun; 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() { 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`); this.lastRun = curTime; 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() { const now = new Date(); // 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); return cron; }