如何让 while 循环暂停指定时间(日期时间)?

发布于 2025-01-10 00:12:22 字数 171 浏览 1 评论 0原文

我想让 while 循环运行,里面发生的事情大约需要 2 秒才能完成(它变化很小),所以如果我使用 time.sleep(60 或 58)它仍然会稍微改变。所以我想做的是 while 循环在 16:00:00 开始(因为我单击运行)并执行其操作,等待然后在 16:01:00 再次开始,所以一分钟后等等在。我怎样才能做到这一点?

I would like to let a while loop run, the stuff thats happening inside takes about 2 seconds to complete (it varies a small amount), so if I use time.sleep(60 or 58) it would still shift slightly. So what I would like to do is that the while loop starts for example at 16:00:00 (because I click run) and does its stuff, waits and then starts again at 16:01:00, so a minute later and so on. How can I do that?

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

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

发布评论

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

评论(2

彡翼 2025-01-17 00:12:22

测量操作所花费的时间。然后从循环周期中减去该时间即可得到睡眠时间。

import time

while True:
    start = time.time()
    # do your thing
    time.sleep(60 - (time.time() - start))

Measure the time taken by the operation. Then subtract that from your loop period to get the amount of time to sleep.

import time

while True:
    start = time.time()
    # do your thing
    time.sleep(60 - (time.time() - start))
相对绾红妆 2025-01-17 00:12:22

您将 time.sleep() 放在代码中的什么位置?当所有处理完成时,您是否尝试过将其放在 while 循环的末尾?

Where are you putting time.sleep() in your code? Have you tried putting it at the end of the while loop when all of the processing is complete?

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