- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有 2 个 node.js 网络服务器。我在网络服务器中缓存数据。我根据系统时间同步缓存加载/清除。我已经完成了所有主机的时间同步。
现在我使用以下代码每 15 分钟清除一次缓存:
millisTillNexthour = "Calculate millis remaining until next hour"
setTimeout(function() {
setInterval(function() {
cache.clear();
}, 60000*15);
}, millisTillNexthour);
我的预期是,即使这个进程一直运行,缓存也会在一天中的每个小时的第 15 分钟清除一次。
我的问题是:setInterval 会随时间漂移吗?
例如:现在它在 10:00 10:15 10:30 10:45 11:00 ...... 清除缓存
setInterval 应该在系统时间 10:15 清除缓存,而不是系统时间 10:15,而是在系统时间 10:20 执行,这会发生吗?
我不确定这是如何工作的。请说明一下。我希望我能很好地解释我的问题。
最佳答案
我可能来晚了一点,但这就是我解决这个特殊时间滑动问题的方法,使用递归调用的 setTimeout() 函数而不是使用 setInterval()。
var interval = 5000;
var adjustedInterval = interval;
var expectedCycleTime = 0;
function runAtInterval(){
// get timestamp at very start of function call
var now = Date.now();
// log with time to show interval
console.log(new Date().toISOString().replace(/T/, ' ').replace(/Z/, '') + " runAtInterval()");
// set next expectedCycleTime and adjustedInterval
if (expectedCycleTime == 0){
expectedCycleTime = now + interval;
}
else {
adjustedInterval = interval - (now - expectedCycleTime);
expectedCycleTime += interval;
}
// function calls itself after delay of adjustedInterval
setTimeout(function () {
runAtInterval();
}, adjustedInterval);
}
在每次迭代中,该函数都会根据先前计算的预期时间检查实际 执行时间,然后从“interval”中扣除差值以生成“adjustedInterval”。这种差异可能是正数也可能是负数,结果表明实际执行时间往往在“真实”值 +/- ~5 毫秒左右波动。
无论哪种方式,如果你有一个每分钟执行一次的任务,并且你运行它一整天,使用这个函数你可以预期 - 对于一整天 - 每个小时都会有 60 次迭代发生。您不会遇到偶尔的一小时只得到 59 个结果的情况,因为最终整整一分钟都已经过去了。
关于javascript - setInterval 可以随时间漂移吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18167059/
我希望创建能够快速重复的功能 - 大约 50 毫秒。然而,我需要在调用中尽可能保持一致性,并且我发现 NSTimer 有点不稳定。看来我可能会从 mach_absolute_time 找到一些保持时间
根据 API 文档以及之前的 SO threads , SystemClock.elapsedRealtime() 应该即使在设备处于 sleep 状态时也能保持准确的时间。这不是我观察到的。 我编写
我想开发在谷歌地图上绘制当前位置的应用程序。在这里,我通过 LocationManager(GPS 提供商和网络提供商)的 onLocationChanged 获取位置详细信息。我能够获取位置详细信息
我有一个使用 MKMapView 的简单 iPhone 应用程序。它有一个分段控件,可以调整要缩放的区域(街道、社区、城市、州、世界)。它工作正常,但如果我缩小到州级别并回到街道,我注意到中心点已经移
我正在尝试在连接到本地 NTP 服务器的 Mac 上获取实际的 NTP 漂移。 读取/var/db/ntp.drift 文件时,根据PPM to milliseconds conversion 得到-
我有一个 AWS Cloud Formation 堆栈。我启动并停止了该堆栈中的 EC2 实例。现在堆栈已漂移,下面是漂移结果。我该如何解决这个问题,因为预期和实际都是相同的。 最佳答案 我不相信这与
我是一名优秀的程序员,十分优秀!