Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a function at specific time & date?

How can I run a function at a given time and date?

Example: I have a function that needs to run on the 12th of each month at 10AM.

This page will be running 24/7, if this is important.

Obviously I'd have to compare against the current date, but I'm not sure how to check if the current date and time has been matched.

Shannon

like image 759
Shannon Hochkins Avatar asked Sep 30 '13 06:09

Shannon Hochkins


People also ask

How do you call a function at a specific time?

setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.

How do you cause a function to be invoked at a specified time later?

You can use JavaScript Timing Events to call function after certain interval of time: This shows the alert box every 3 seconds: setInterval(function(){alert("Hello")},3000); You can use two method of time event in javascript.

How can I get specific time in JavaScript?

JavaScript Date getTime() getTime() returns the number of milliseconds since January 1, 1970 00:00:00.

How do you call a function after some time in react?

The setTimeout method allows us to run a function once after the interval of the time. Here we have defined a function to log something in the browser console after 2 seconds. const timerId = setTimeout(() => { console. log('Will be called after 2 seconds'); }, 2000);


2 Answers

It's not advised to use setInterval because it has non-deterministic behaviour - events can be missed, or fire all at once. Time will fall out of sync, too.

The code below instead uses setTimeout with a one minute period, where each minute the timer is resynchronised so as to fall as closely to the hh:mm:00.000s point as possible.

function surprise(cb) {
    (function loop() {
        var now = new Date();
        if (now.getDate() === 12 && now.getHours() === 12 && now.getMinutes() === 0) {
            cb();
        }
        now = new Date();                  // allow for time passing
        var delay = 60000 - (now % 60000); // exact ms to next minute interval
        setTimeout(loop, delay);
    })();
}
like image 173
Alnitak Avatar answered Sep 26 '22 09:09

Alnitak


On the page where o want to do the check add this

setInterval(function () {
    var date = new Date();
    if (date.getDate() === 12 && date.getHours() === 10 && date.getMinutes === 0) {
        alert("Surprise!!")
    }
}, 1000)

FIDDLE


Update- add date.getSeconds == 0 to limit it to fire only one at 10:00:00. Thanks to comments below

like image 24
bhb Avatar answered Sep 25 '22 09:09

bhb