The easiest way I could see you doing this, was an Object with each action saved to a time. I choose to use <HOUR><MINUTE>
to store each value. So a 4:12PM time would be: 1612
. Then a setInterval
to run every minute and check if it needs todo a new action.
function hello() {
console.log('Hello');
}
let actions = {
"0630": function() {
console.log('Its 6:30');
},
"1200": hello, //NOON
"1400": hello, //2:00 PM
"0000": function() {
console.log('New Day / Midnight');
},
};
let codeStartTime = new Date();
function checkActions() {
let date = new Date();
let action = actions[`${date.getHours() >= 10 ? "" : "0"}${date.getHours()}${date.getMinutes() >= 9 ? "" : "0"}${date.getMinutes()}`];
if (typeof action === "function") action(); //If an action exists for this time, run it.
}
setTimeout(function() {
checkActions();
setInterval(checkActions, 60000); //Run the function every minute. Can increase/decrease this number
}, ((60 - codeStartTime.getSeconds()) * 1000) - codeStartTime.getMilliseconds()); // Start the interval at the EXACT time it starts at a new minute
/** CODE for the Stack Overflow Snippet **/
console.log(`Starting first interval in ${((60 - codeStartTime.getSeconds()))} seconds.`);
console.log(`Adding in StackOverflow function, set to run at: ${codeStartTime.getHours() >= 10 ? "" : "0"}${codeStartTime.getHours()}${codeStartTime.getMinutes() >= 9 ? "" : "0"}${codeStartTime.getMinutes() + 1}`);
actions[`${codeStartTime.getHours() >= 10 ? "" : "0"}${codeStartTime.getHours()}${codeStartTime.getMinutes() >= 9 ? "" : "0"}${codeStartTime.getMinutes() + 1}`] = function() {
console.log('Ran the StackOverflow Function');
};
If you choose to, you can wait for the any of my example times in the actions
Object just to prove it works. But the StackOverflow code just adds a sample time to your current time +1 minute in the actions
Object just to make it easier to see it in action.
setInterval
is used here just to be simple, but not really recommended if this will run all day. Reason Why.
To have a more exact time, I suggest replacing the setInterval
to a setTimeout
and just re-define the setTimeout
everytime it's ran.