睡到下一秒

发布于 2024-09-15 20:09:02 字数 225 浏览 0 评论 0原文

我发现经常需要等到下一秒才能执行一系列操作中的下一个操作。这大大减慢了单元测试的速度。所以这是我的问题:

除了执行 Thread.sleep(1000) 之外,是否有一种更快更有效的方法来睡眠,直到第二秒更改为下一秒?

假设时间是 1:00:89

我会睡一秒到 1:01:89

我宁愿在时间达到 1:01 时继续执行 或尽可能接近。

这合理可能吗? ^_^

I am finding often the need to very often wait until the next second to do the next operation in a series. This slows down unit tests quite considerably. So here's my question:

Instead of doing Thread.sleep(1000) is there a quicker more efficient way to sleep until the second changes to the next second?

Say the time is 1:00:89

I sleep one second to 1:01:89

I would rather continuing executing when the time hits 1:01
or as close as possible.

Is this reasonably possible? ^_^

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我要还你自由 2024-09-22 20:09:02

好吧,你可以这样做:

long millisWithinSecond = System.currentTimeMillis() % 1000;
Thread.sleep(1000 - millisWithinSecond);

请注意,这不会准确 - 你可能需要迭代,这有点混乱。

不过,最好根本不睡觉。你能注入一个“睡眠服务”,让你在测试中伪造睡眠吗? (我很少需要这样做,但我经常注入一个假时钟来报告不同的时间。)在生产代码中休眠的目的是什么?

Well, you could do something like:

long millisWithinSecond = System.currentTimeMillis() % 1000;
Thread.sleep(1000 - millisWithinSecond);

It won't be exact, mind you - you may need to iterate, which is a bit messy.

However, it would be better not to have to sleep at all. Could you inject a "sleeping service" which would allow you to fake the sleeps out in tests? (I've rarely needed to do that, but I've often injected a fake clock to report different times.) What's the purpose of sleeping in the production code at all?

或十年 2024-09-22 20:09:02

当你说“秒”时,你是指系统时钟的秒吗?您可以通过 System.currentTimeMillis() 获取当前时间(以毫秒为单位),然后从 1000 中减去该时间并睡眠该时间,但请记住 Thread.sleep() 并不完全准确,因此不要这样做如果您稍微超出一点,请不要感到惊讶。

When you say "the second", do you mean the second of the system clock? You can get the current time in milliseconds via System.currentTimeMillis(), then subtract that from 1000 and sleep by that amount, but keep in mind that Thread.sleep() is not perfectly accurate, so don't be surprised if you overshoot by a bit.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文