在JavaScript中,如何在特定时间运行函数? [英] In JavaScript, how can I have a function run at a specific time?

查看:152
本文介绍了在JavaScript中,如何在特定时间运行函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个托管仪表板的网站:我可以在页面上编辑JavaScript,而且我现在每隔五秒刷新一次。

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.

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

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

我怎么能这样做?

推荐答案

JavaScript 不是这个工具。如果你想在每天的特定时间运行某些东西,你几乎肯定会找到一些本地运行的东西,比如 python applescript

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 python or applescript.

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

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.

首先,你必须创建一个 new Date()并设置一个检查间隔,以查看小时是否为8(上午8点)。

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).

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

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)

它不会在完全执行 8点钟(除非你在分钟开始运行),因为它每分钟检查一次 。您可以尽可能地减少间隔,以提高检查的准确性,但这样做有点过分:它会每小时检查 每小时 每天看看是否是8点。

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.

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

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.

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

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.

话虽如此,您可能想要执行或编写Automator工作流程等内容对于OS X上的预定任务。

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

如果您需要更多与平台无关的内容,我会认真考虑一下 Python Bash

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

作为更新,自动化JavaScript ,它似乎提供了一种可行的方式来使用JavaScript来做这类事情(虽然显然你不是在相同的上下文中使用它; Apple只是为您提供了在本地使用其他脚本语言的界面。

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).

如果您使用的是OS X并且真的想使用JavaScript,我认为这就是方法要发布。

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

与上述相关的发布说明似乎是撰写本文时的唯一现有文件(约塞米特向公众发布后约2个月),但他们值得一读。您还可以查看 javascript-automation 标记了一些例子。

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 javascript-automation tag for some examples.

我还找到了 JXA Cookbook 非常非常有帮助。

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. 在Automator中创建一个空白的应用程序。


    • 打开Automator.app(它应该在你的Applications目录中)并创建一个新文档。

    • 来自对话框,选择应用程序。


  • 下一步是实际添加将要执行的JavaScript。为此,首先从侧边栏向工作流添加运行JavaScript操作。

编写JavaScript。

Write the JavaScript.


  • 这是你需要的地方在继续之前知道你想做什么。根据您提供的内容,我假设您要在Safari中加载的页面上执行 window.print()。你可以这样做(或者更常见的是,在Safari选项卡中执行任意JS):

  • 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 });


  • 你可能需要调整哪个 windows 您正在访问,具体取决于您的设置。

  • You might have to adjust which of the windows you're accessing depending on your setup.

    • 保存(文件 - >保存 + S )将文件作为应用程序放在您可以找到的位置(或iCloud)。

    • Save (File -> Save or +S) the file as an Application in a location you can find (or iCloud).

    • 打开日历(或iCal)。

    • 创建一个新事件并为其指定一个可识别的名称;然后,将时间设置为所需的运行时间(在这种情况下为上午8:00)。

    • 将事件设置为每天重复(或每周,每月等等 - 但通常是你的' d喜欢它运行)。

    • 将警报(或警报,取决于您的版本)设置为自定义。

    • 选择打开文件,选择您保存的应用程序文件。

    • 为警报计时选项选择事件发生时。

    • 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.

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

    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.

    这篇关于在JavaScript中,如何在特定时间运行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆