Created
May 5, 2017 07:43
-
-
Save liesislukas/df1ee4c53cb4205c36e29269a2b74b7a to your computer and use it in GitHub Desktop.
Node.js cron runner. Interval is set using moment.js add() function. Check sample code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Sample usage: | |
runCron({promise: screenshotsCache, intervalNumber: 5, intervalString: 'minutes'}); | |
This will call "screenshotsCache" Promise every 5 minutes. | |
If promise resolves after 6 minutes, it will be called again immediately because 5 mins already passed. | |
*/ | |
const moment = require('moment'); | |
export default function runCron({promise, intervalNumber, intervalString}) { | |
console.log('--- START CRON ---'); | |
let start = moment(); | |
let end = null; | |
let nextAt = null; | |
const checkIfRunAgainAlready = () => { | |
if (moment().isSameOrAfter(nextAt)) { | |
return runCron({promise, intervalNumber, intervalString}); | |
} else { | |
setTimeout(() => { | |
checkIfRunAgainAlready(); | |
}, 1000); | |
} | |
}; | |
const afterEnd = () => { | |
if (end === null) { | |
end = moment(); | |
console.log(`~~~~ CRON DONE IN ${end.diff(start)} ms. ~~~~`); | |
checkIfRunAgainAlready(); | |
} | |
if (nextAt === null) { | |
nextAt = start.add(intervalNumber, intervalString); | |
} | |
}; | |
promise() | |
.then(() => { | |
afterEnd(); | |
}) | |
.catch((e) => { | |
console.error('#skdlfks CRON error: ', e); | |
afterEnd(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment