Skip to content

Instantly share code, notes, and snippets.

@mreis1
Last active May 26, 2020 10:30
Show Gist options
  • Select an option

  • Save mreis1/2cb09d2ff2fc87d525d68f2af6a88f0a to your computer and use it in GitHub Desktop.

Select an option

Save mreis1/2cb09d2ff2fc87d525d68f2af6a88f0a to your computer and use it in GitHub Desktop.
Execute callback on time (schedule)
/***
Usage:
scheduleWarning('05:00:00',()=>console.log(new Date().toString())
*/
function scheduleWarning(time, triggerThis, adjust){
const ensureValidNum = (v, d, min, max) => {
if (!(typeof v === 'number' && !isNaN(v))) {
return d;
}
if (!(v >= min && v <= max)) { return d; }
return v;
}
const parts = time.split(':');
// get hour and minute from hour:minute param received, ex.: '16:00'
const hour = ensureValidNum(parts[0], 0, 0, 23)
const minute = ensureValidNum(parts[1], 0, 0, 59)
const seconds = ensureValidNum(parts[2], 0, 0, 59);
// create a Date object at the desired timepoint
const startTime = new Date();
startTime.setHours(hour, minute, seconds);
let now = new Date();
// increase timepoint by 24 hours if in the past
if (startTime.getTime() < now.getTime()) {
startTime.setHours(startTime.getHours() + 24);
}
// get the interval in ms from now to the timepoint when to trigger the alarm
const firstTriggerAfterMs = startTime.getTime() - now.getTime();
// trigger the function triggerThis() at the timepoint
// create setInterval when the timepoint is reached to trigger it every day at this timepoint
setTimeout(() => {
triggerThis();
setInterval(triggerThis, 24 * 60 * 60 * 1000);
}, firstTriggerAfterMs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment