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

查看:50
本文介绍了在 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.

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

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

我怎么能这样做?

推荐答案

JavaScript 不是 用于此的工具.如果你想在每天的特定时间运行一些东西,你几乎肯定会寻找在本地运行的东西,比如 .

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.

话虽如此,您可能想要执行之类的操作,或者为 OS X 上的计划任务编写 Automator 工作流.

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

如果你需要更多平台无关的东西,我会认真考虑看看PythonBash.

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

作为更新,引入了JavaScript for Automation使用 OS X Yosemite,它似乎提供了一种将 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 个月),但它们值得一读.您还可以查看 标签的一些例子.

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非常很有帮助.

您可能需要稍微调整这种方法以适应您的特定情况,但我会给出一个总体概述.

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(它应该在您的应用程序目录中)并创建一个新文档.
    • 从对话框中选择应用程序".
  • 下一步是实际添加将要执行的 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.
    • 将文件保存(File -> Save+S)作为应用程序保存在您可以找到的位置(或 iCloud).
    • Save (File -> Save or +S) the file as an Application in a location you can find (or iCloud).
    • 打开日历(或 iCal).
    • 创建一个新事件并为其指定一个可识别的名称;然后,将时间设置为所需的运行时间(在本例中为上午 8:00).
    • 将活动设置为每天重复(或每周、每月等 - 无论您希望它运行的频率如何).
    • 将警报(或警报,取决于您的版本)设置为自定义.
    • 选择打开文件"并选择您保存的应用程序文件.
    • 为警报时间选项选择在事件发生时".

    就是这样!每次将事件设置为运行时,您在应用程序文件中编写的 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天全站免登陆