UNPKG

dont-sleep

Version:

Para servidores Heroku não entrar em modo Idle

65 lines (56 loc) 2.04 kB
// This script will run every 20 minutes to keep a heroku dyno awake and running, thereby eliminating potentially very long wait time as sleeping server restarts // Import into main file and invoke right after starting up server, passing in the heroku url const fetch = require("node-fetch"); const timeToNap = require("./naptime.js"); const dontSleep = (options) => { let url; if (typeof options === "string") { url = options; } else { url = options.url; } let interval = options.interval * 60000 || 60000; let startNap = options.startNap || [0, 0, 0, 0]; let endNap = options.endNap || [0, 0, 0, 1]; const minutes = interval / 60000; const minuteString = `${minutes} ${minutes === 1 ? "minute" : "minutes"}`; console.log(`Dont sleep called with an interval of ${minuteString}.`); const runTimer = (timerInterval) => { const timeoutFn = () => { timerInterval = interval; const naptime = timeToNap(startNap, endNap, new Date(Date.now())); if (naptime) { const napString = `${(naptime / 60000).toFixed(2)} ${ minutes === 1 ? "minute" : "minutes" }`; console.log(`It's naptime! Napping for ${napString}...`); return runTimer(naptime); } fetch(url) .then((response) => { console.log( `Status: ${response.status} | Fetching ${url}. Dyno is woke.\nNext fetch request in ${minuteString}...` ); }) .catch((error) => console.log(`Error fetching ${url}: ${error.message}`) ); clearTimeout(timeoutId); return runTimer(timerInterval); // run timer with original interval }; const timeoutId = setTimeout(timeoutFn, timerInterval); return timeoutId; }; const start = () => { try { return runTimer(interval); } catch (error) { console.log("setTimeout error:", error.message); } }; return { start, runTimer, }; }; module.exports = dontSleep;