这是可行的,在javascript中单调递增的timeId吗?

时间:2018-11-04 15:03:53

标签: javascript node.js time

[NodeJS 10.x / 11.x]

我正在寻找一个始终增加的时间“ id”,它在进程之间(但不一定在服务器之间)是唯一且单调增加的。我看过Monotonically increasing time in Node.js,但这是为了提高性能。基本上,我正在寻找一个可以持久保存到数据库中的timeId。

注意:我已经尝试过process.hrTime(),但是在我的MacMini上,它并没有单调增加。升级到Node10 / 11并使用hrtime.bigInt()似乎可以解决部分问题。

这是我目前的想法(其中省略了bigIntToBase64String(),但符合您的期望):

let startHrTime = process.hrtime.bigint();
let systemStartTime = BigInt(new Date().getTime()) * BigInt(2**16) * BigInt(2**5);

class TimeId {
    getTimeId() {
        let t1 = process.hrtime.bigint() - startHrTime;
        let ticks = t1 + systemStartTime;
        return this.bigIntToBase64String(ticks);
    };
}

如您所见,这有点骇人听闻。我减去我得到的第一个小时,然后将其添加到系统启动时间(我已将其整合为BigInt)。假设时钟完全同步(ha!),则可以将其用作全局timeId。 (出于我的目的,希望以另一种方式解决跨系统时钟偏差)。

我目前正在配置一些测试以验证我的假设,但是,由于我对JavaScript / Node.JS还是很陌生,所以我想问一下...这是一种合理的方法吗?

0 个答案:

没有答案