In JavaScript, how can I have a function run at a specific time?
Asked Answered
O

6

24

I have a website that hosts a dashboard: I can edit the JavaScript on the page and I currently have it refreshing every five seconds.

I am trying to now get a window.print() to run every day at 8 AM.

How could I do this?

Odontalgia answered 14/7, 2014 at 16:42 Comment(6)
JavaScript on a web page really doesn't sound like the right tool for this...Gauguin
JS has no scheduling features for a fixed time. You can take the current time, figure out when 8am is, and set a timeout for that interval. But that's all pointless unless you keep a browser open on that page. Simply having some JS in html doesn't make it executable until the page is actually being viewed in a browser, or you're using server-side JS, like node.jsArron
I guess you are using setInterval method. In that method see if diffrence between 8 am and current time is less than 5 secs. If so do a setTimeOut to print , with diff in time. But your browser needs to be open at that timeIslet
You understand that JavaScript only runs when you open the page in your browser, right?Goose
Keep in mind that print usually requires some user confirmation to go through, and browsers can also do strange things to setTimeout when the tab/window is inactive.Koski
As a constructive suggestion (but not a complete answer) - consider running a cron job to run use PhantomJS to hit your dashboard and render the results to a PDF file which can be emailed or printed from there.Leblanc
M
65

JavaScript is not the tool for this. If you want something to run at a specific time every day, you're almost certainly looking for something that runs locally, like or .


However, let's consider for a moment that JavaScript is your only option. There are a few ways that you could do this, but I'll give you the simplest.

First, you'll have to to create a new Date() and set a checking interval to see whether the hour is 8 (for 8 AM).

This will check every minute (60000 milliseconds) to see if it is eight o'clock:

window.setInterval(function(){ // Set interval for checking
    var date = new Date(); // Create a Date object to find out what time it is
    if(date.getHours() === 8 && date.getMinutes() === 0){ // Check the time
        // Do stuff
    }
}, 60000); // Repeat every 60000 milliseconds (1 minute)

It won't execute at exactly 8 o'clock (unless you start running this right on the minute) because it is checking once per minute. You could decrease the interval as much as you'd like to increase the accuracy of the check, but this is overkill as it is: it will check every minute of every hour of every day to see whether it is 8 o'clock.

The intensity of the checking is due to the nature of JavaScript: there are much better languages and frameworks for this sort of thing. Because JavaScript runs on webpages as you load them, it is not meant to handle long-lasting, extended tasks.

Also realize that this requires the webpage that it is being executed on to be open. That is, you can't have a scheduled action occur every day at 8 AM if the page isn't open doing the counting and checking every minute.

You say that you are already refreshing the page every five seconds: if that's true, you don't need the timer at all. Just check every time you refresh the page:

var date = new Date(); // Create Date object for a reference point
if(date.getHours() === 8 && date.getMinutes() === 0 && date.getSeconds() < 10){ // Check the time like above
   // Do stuff
}

With this, you also have to check the seconds because you're refreshing every five seconds, so you would get duplicate tasks.


With that said, you might want to do something like this or write an Automator workflow for scheduled tasks on OS X.

If you need something more platform-agnostic, I'd seriously consider taking a look at Python or Bash.


As an update, JavaScript for Automation was introduced with OS X Yosemite, and it seems to offer a viable way to use JavaScript for this sort of thing (although obviously you're not using it in the same context; Apple is just giving you an interface for using another scripting language locally).

If you're on OS X and really want to use JavaScript, I think this is the way to go.

The release notes linked to above appear to be the only existing documentation as of this writing (which is ~2 months after Yosemite's release to the public), but they're worth a read. You can also take a look at the tag for some examples.

I've also found the JXA Cookbook extremely helpful.

You might have to tweak this approach a bit to adjust for your particular situation, but I'll give a general overview.

  1. Create a blank Application in Automator.
    • Open Automator.app (it should be in your Applications directory) and create a new document.
    • From the dialog, choose "Application." Automator new document dialog
  2. Add a JavaScript action.
    • The next step is to actually add the JavaScript that will be executed. To do that, start by adding a "Run JavaScript" action from the sidebar to the workflow. Drag the JS file into the workflow
  3. Write the JavaScript.

    • This is where you'll have to know what you want to do before proceeding. From what you've provided, I'm assuming you want to execute window.print() on a page loaded in Safari. You can do that (or, more generally, execute arbitrary JS in a Safari tab) with this:

      var safari = Application('Safari');
      safari.doJavaScript('window.print();', { in: safari.windows[0].currentTab });
      
    • You might have to adjust which of the windows you're accessing depending on your setup.
  4. Save the Application.
    • Save (File -> Save or +S) the file as an Application in a location you can find (or iCloud).
  5. Schedule it to run.
    • Open Calendar (or iCal).
    • Create a new event and give it an identifiable name; then, set the time to your desired run time (8:00 AM in this case).
    • Set the event to repeat daily (or weekly, monthly, etc. – however often you'd like it to run).
    • Set the alert (or alarm, depending on your version) to custom.
    • Choose "Open file" and select the Application file that you saved.
    • Choose "At time of event" for the alert timing option. GIF instructions for scheduling the event

That's it! The JavaScript code that you wrote in the Application file will run every time that event is set to run. You should be able to go back to your file in Automator and modify the code if needed.

Monarda answered 14/7, 2014 at 16:47 Comment(11)
@Goose How so? if you're referring to the fact that it won't run at exactly 8:00, it will run at some point during that minute. If the OP wants to be more precise, s/he could decrease the interval, but it is overkill as it is.Monarda
Note: This will trigger at up to 60 seconds after 8 AM. And @Christophe, yes this does run at 8 AM every day (as long as the page is open), because the interval isn't canceled.Koski
I am referring to the fact that JavaScript won't run unless a user actually has the page open at that specific time. I am afraid the OP is confusing client side scripting with scheduled jobs.Goose
Since the OP is refreshing the page every 5 seconds, the timer will get reset with each load...Leblanc
@MattJohnson I missed that: I'll add something for that.Monarda
@Monarda I have removed the downvote (the disclaimer must have been added after my initial comment).Goose
Sooo... if the page is refreshed every 5 seconds, then there could be 10 to 12 hits, depending on how long the the page takes to load. Right? Perhaps a cookie is in order here. Else that's a lot of extra printing... :DLeblanc
@MattJohnson Yes: that's also a problem: JavaScript/web is not meant to do this. I added a check for seconds that should prevent duplicates.Monarda
Hi OP here. I am running local scripts to do other actions. Is there a way I could get the page to print via a perl script (due to you all saying this is not a very good use of the javascript)?Odontalgia
@Odontalgia I'm afraid that would have to be an entirely different question: I don't know Perl, so that would be a different subject with a different answer.Monarda
It is a good use of Javascript. Use Node.js for local tasks like this.Azoth
A
10
function every8am (yourcode) {
    var now = new Date(),
        start,
        wait;

    if (now.getHours() < 7) {
        start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0);
    } else {
        start = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 8, 0, 0, 0);
    }

    wait = start.getTime() - now.getTime();

    if(wait <= 0) { //If missed 8am before going into the setTimeout
        console.log('Oops, missed the hour');
        every8am(yourcode); //Retry
    } else {
        setTimeout(function () { //Wait 8am
            setInterval(function () {
                yourcode();
            }, 86400000); //Every day
        },wait);
    }
}

To use it:

var yourcode = function () {
        console.log('This will print evryday at 8am');
    };
every8am(yourcode);

Basically, get the timestamp of now, the timestamp of today 8am if run in time, or tomorrow 8am, then set a interval of 24h to run the code everyday. You can easily change the hour it will run by setting the variable start at a different timestamp.

I don t know how it will be useful to do that thought, as other pointed out, you ll need to have the page open all day long to see that happen...

Also, since you are refreshing every 5 seconds:

function at8am (yourcode) {
    var now = new Date(),
        start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0);

    if (now.getTime() >= start.getTime() - 2500 && now.getTime() < start.getTime() + 2500) {
        yourcode();
    }
}

Run it the same way as every8am, it look if 8am is 2.5second ahead or behind, and run if it does.

Akins answered 26/8, 2014 at 15:47 Comment(0)
H
4

I try to give my answer hoping it could help:

    function startJobAt(hh, mm, code) {
        var interval = 0;
        var today = new Date();
        var todayHH = today.getHours();
        var todayMM = today.getMinutes();
        if ((todayHH > hh) || (todayHH == hh && todayMM > mm)) {
            var midnight = new Date();
            midnight.setHours(24,0,0,0);
            interval = midnight.getTime() - today.getTime() +
                    (hh * 60 * 60 * 1000) + (mm * 60 * 1000);
        } else {
            interval = (hh - todayHH) * 60 * 60 * 1000 + (mm - todayMM) * 60 * 1000;
        }
        return setTimeout(code, interval);
    }

With the startJobAt you can execute only one the task you wish, but if you need to rerun your task It's up to you to recall startJobAt.

bye

Ps

If you need an automatic print operation, with no dialog box, consider to use http://jsprintsetup.mozdev.org/reference.html plugin for mozilla or other plugin for other bowsers.

Hyracoid answered 25/8, 2014 at 19:6 Comment(0)
H
3

I will suggest to do it in Web Worker concept, because it is independent of other scripts and runs without affecting the performance of the page.

  1. Create a web worker (demo_worker.js)

    var i = 0;
    var date = new Date();
    var counter = 10;
    var myFunction = function(){
        i = i + 1;
        clearInterval(interval);
        if(date.getHours() === 8 && date.getMinutes() === 0) {
            counter = 26280000;
            postMessage("hello"+i);
        }    
        interval = setInterval(myFunction, counter);
    }
    var interval = setInterval(myFunction, counter);
    
  2. Use the web worker in Ur code as follows.

    var w;    
    function startWorker() {
        if (typeof(Worker) !== "undefined") {
            if (typeof(w) == "undefined") {
                w = new Worker("demo_worker.js");
                w.onmessage = function(event) {
                    window.print();
                };
            } else {
                document.getElementById("result").innerHTML = "Sorry, your browser does not support HTML5 Web Workers";
            }
        }
    }
    

I think it will help you.

Heterodyne answered 27/8, 2014 at 7:21 Comment(0)
D
2

I have written function which

  • allows expressing delay in seconds, new Date() format and string's new Date format
  • allows cancelling timer

Here is code:

"use strict"
/**
  This function postpones execution until given time.
  @delay might be number or string or `Date` object. If number, then it delay expressed in seconds; if string, then it is parsed with new Date() syntax. Example:
      scheduleAt(60, function() {console.log("executed"); }
      scheduleAt("Aug 27 2014 16:00:00", function() {console.log("executed"); }
      scheduleAt("Aug 27 2014 16:00:00 UTC", function() {console.log("executed"); }
  @code function to be executed
  @context @optional `this` in function `code` will evaluate to this object; by default it is `window` object; example:
      scheduleAt(1, function(console.log(this.a);}, {a: 42})
  @return function which can cancel timer. Example:
      var cancel=scheduleAt(60, function(console.log("executed.");});
      cancel();
      will never print to the console.
*/

function scheduleAt(delay, code, context) {

    //create this object only once for this function
    scheduleAt.conv = scheduleAt.conv || {
        'number': function numberInSecsToUnixTs(delay) {
            return (new Date().getTime() / 1000) + delay;
        },
        'string': function dateTimeStrToUnixTs(datetime) {
            return new Date(datetime).getTime() / 1000;
        },
        'object': function dateToUnixTs(date) {
            return date.getTime() / 1000;
        }
    };

    var delayInSec = scheduleAt.conv[typeof delay](delay) - (new Date().getTime() / 1000);

    if (delayInSec < 0) throw "Cannot execute in past";

    if (debug) console.log('executing in', delayInSec, new Date(new Date().getTime() + delayInSec * 1000))

    var id = setTimeout(
        code,
        delayInSec * 1000
    );

    //preserve as a private function variable setTimeout's id
    return (function(id) {
        return function() {
            clearTimeout(id);
        }
    })(id);
}

Use this as follows:

scheduleAt(2, function() {
    console.log("Hello, this function was delayed 2s.");
});

scheduleAt(
    new Date().toString().replace(/:\d{2} /, ':59 '),
    function() {
        console.log("Hello, this function was executed (almost) at the end of the minute.")
    }
);

scheduleAt(new Date(Date.UTC(2014, 9, 31)), function() {
    console.log('Saying in UTC time zone, we are just celebrating Helloween!');
})
Discretional answered 26/8, 2014 at 13:55 Comment(0)
A
0

setInterval(() => {
  let t = `${new Date().getHours() > 12 ? new Date().getHours() - 12 : new Date().getHours()}:${new Date().getMinutes().length < 2 ? '0' + new Date().getMinutes() : new Date().getMinutes()}:${new Date().getSeconds().length < 2 ? '0' + new Date().getSeconds() : new Date().getSeconds()} ${new Date().getHours()>12?"pm":"am"}`
  console.log(t);
}, 1000);
Aeromancy answered 5/7, 2022 at 17:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.