在JavaScript中,如何让函数在特定时间运行?

在JavaScript中,如何让函数在特定时间运行?,javascript,time,intervals,python,applescript,javascript-automation,Javascript,Time,Intervals,Python,Applescript,Javascript Automation,我有一个网站,上面有一个仪表板:我可以编辑页面上的JavaScript,目前每五秒钟刷新一次 我现在正试图在每天早上8点运行一个window.print() 我怎样才能做到这一点呢?JavaScript不是实现这一点的工具。如果你想在每天的某个特定时间运行某个程序,那么你几乎肯定在寻找本地运行的程序,比如或 但是,让我们考虑一下JavaScript是你唯一的选择。有几种方法可以做到这一点,但我会给你最简单的 首先,您必须创建一个新日期(),并设置一个检查间隔,以查看小时数是否为8(对于上午8点

我有一个网站,上面有一个仪表板:我可以编辑页面上的JavaScript,目前每五秒钟刷新一次

我现在正试图在每天早上8点运行一个
window.print()

我怎样才能做到这一点呢?

JavaScript不是实现这一点的工具。如果你想在每天的某个特定时间运行某个程序,那么你几乎肯定在寻找本地运行的程序,比如或


但是,让我们考虑一下JavaScript是你唯一的选择。有几种方法可以做到这一点,但我会给你最简单的

首先,您必须创建一个
新日期()
,并设置一个检查间隔,以查看小时数是否为8(对于上午8点)

这将每分钟(60000毫秒)检查一次,查看是否为8点钟:

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)
它不会在8点钟执行(除非您在一分钟内开始正确运行),因为它每分钟检查一次。您可以尽可能减少间隔时间,以提高检查的准确性,但这样做太过分了:它将每天每分钟检查一次,看是否是8点

检查的强度取决于JavaScript的性质:有更好的语言和框架用于这类事情。因为JavaScript在加载网页时会在网页上运行,所以它并不意味着要处理持久的、扩展的任务

还要认识到,这需要打开正在执行该操作的网页。也就是说,如果页面没有打开,每分钟都进行计数和检查,则不能在每天上午8点进行预定操作

你说你已经每五秒钟刷新一次页面:如果是这样,你根本不需要定时器。每次刷新页面时只需检查:

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
}
  • 根据您的设置,您可能需要调整正在访问的
    窗口中的哪一个
  • 保存应用程序。
    • 保存(
      文件->保存
      或⌘+S) 将文件作为应用程序保存在您可以找到的位置(或iCloud)
  • 安排它运行。
    • 打开日历(或iCal)
    • 创建一个新事件并为其指定一个可识别的名称;然后,将时间设置为所需的运行时间(本例中为上午8:00)
    • 将事件设置为每天重复(或每周、每月等,不管您希望它运行多久)
    • 将警报(或警报,取决于您的版本)设置为自定义
    • 选择“打开文件”并选择保存的应用程序文件
    • 选择“事件发生时”作为警报计时选项。

  • 就这样!每次将该事件设置为运行时,您在应用程序文件中编写的JavaScript代码都将运行。您应该能够返回到Automator中的文件,并在需要时修改代码。

    我尝试给出我的答案,希望能有所帮助:

        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);
        }
    
    使用startJobAt,您只能执行一个您希望执行的任务,但是如果您需要重新运行您的任务,则由您自行调用startJobAt

    再见

    Ps


    如果你需要一个自动打印操作,没有对话框,考虑使用Mozilla的插件或其他的BooServer插件。< /P> < P>我写了

    函数
    • 允许以秒表示延迟,
      new Date()
      格式和
      string
      new Date
      格式
    • 允许取消计时器
    以下是代码:

    "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);
    }
    
    基本上,获取现在的时间戳,如果及时运行,则获取今天上午8点的时间戳,或者获取明天上午8点的时间戳,然后设置24小时的间隔以每天运行代码。通过将变量start设置为不同的时间戳,可以轻松更改它将运行的小时数

    我不知道这样做会有什么用,正如其他人指出的,你需要整天打开页面才能看到这种情况发生

    另外,由于您每5秒刷新一次:

    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();
        }
    }
    
    上午8点的功能(您的代码){
    var now=新日期(),
    开始=新日期(now.getFullYear(),now.getMonth(),now.getDate(),8,0,0,0);
    如果(now.getTime()>=start.getTime()-2500&&now.getTime()

    以与每个8am相同的方式运行它,查看8am是否领先或落后2.5秒,如果领先或落后,则运行它。

    我建议在Web Worker概念中这样做,因为它独立于其他脚本,运行时不会影响页面的性能

  • 创建一个web工作者(demo_worker.js)

  • 在Ur代码中使用web worker,如下所示

    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";
            }
        }
    }
    

  • 我想这会对你有所帮助。

    网页上的JavaScript听起来确实不是适合这个的工具……JS没有固定时间的调度功能。您可以获取当前时间,计算出上午8点是什么时候,并为该时间间隔设置超时。但这一切都是毫无意义的,除非你在那个页面上打开浏览器。在浏览器中实际查看页面之前,或者您使用服务器端JS(如node.JS),简单地在html中使用一些JS并不能使其可执行。我猜您使用的是setInterval方法。在该方法中,查看上午8点和当前时间之间的差异是否小于5秒。如果是这样,请使用时间差设置打印超时。但是您的浏览器需要在那个时候打开您知道JavaScript只在您在浏览器中打开页面时运行,对吗?请记住,
    print
    通常需要一些用户确认才能通过,并且当选项卡/窗口处于非活动状态时,浏览器也会对设置Timeout做一些奇怪的事情。@Christophe这是怎么回事?如果你指的是它不会在8点运行,它会在那一分钟的某个时间运行。如果OP想要更精确,s/he可以缩短间隔,但这是一种过度杀伤力。注意:这将在上午8点后最多60秒触发。还有@Christophe,是的,每天早上8点运行(只要页面是
    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);
        }
    }
    
    var yourcode = function () {
            console.log('This will print evryday at 8am');
        };
    every8am(yourcode);
    
    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();
        }
    }
    
    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);
    
    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";
            }
        }
    }