简体   繁体   English

如何在一天中的特定时间频繁运行javascript中的function()

[英]How to run function() frequently on specific times of the day in javascript

I have a function which runs every 3 minutes 24/7 using setTimeout(). 我有一个函数,它使用setTimeout()每3分钟24/7运行一次。 The problem is that it fetches data from an API that have an maximum of request a month. 问题在于它从一个月最多有请求的API提取数据。 I want to run it as often as a can but it´s unnecessary to do so when i am a sleep because of the waste of requests. 我想尽可能多地运行它,但是由于浪费请求,在我睡着时不必这样做。 How can in addition only run my script between for example 06:30:00 and 20:00:00? 另外如何仅在06:30:00和20:00:00之间运行我的脚本?

You will need both setTimeout and Date() to achieve this : for eg 您将需要setTimeoutDate()来实现此目的:例如

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
     millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){alert("It's 10am!")}, millisTill10);

For more details please follow this 有关更多详细信息,请遵循

I have tested and verified following code. 我已经测试并验证了以下代码。 Mine is 7:22 PM which comes under these timings and it executes very well. 我的时间是晚上7:22,在这些时间范围内,执行情况非常好。

 // get todays strict timings // 06:30:00 and 20:00:00 setInterval(function() { lowerDate = new Date(); lowerDate.setHours(6); lowerDate.setMinutes(30); lowerDate.setSeconds(0); upperDate = new Date(); upperDate.setHours(20); upperDate.setMinutes(0); upperDate.setSeconds(0); todayDate = new Date(); if (todayDate > lowerDate && todayDate < upperDate) console.log("execute"); // execute only if in between these times }, 3 * 60 * 1000) //Every 3 minutes 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM