使用 while 的等待函数 [英] wait function that uses while

查看:56
本文介绍了使用 while 的等待函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚写了一个看起来像这样的函数:

I just wrote a function that looked like this:

def block_for(seconds):
    """Wait at least seconds, this function should not be affected by the computer sleeping."""
    end_time = datetime.datetime.now() + datetime.timedelta(seconds)

    while datetime.datetime.now() < end_time:
        pass

这有什么不好的吗?理想情况下,while 循环中应该有什么东西吗?

Can anything bad come of this? Should there ideally be something inside the while loop?

推荐答案

也许将 time.sleep(1) 放在 while 循环中会需要更少的周期?或者

maybe putting time.sleep(1) in the while loop will require less cycles? Or

def block_for(seconds):
    """Wait at least seconds, this function should not be affected by the computer sleeping."""
    end_time = datetime.datetime.now() + datetime.timedelta(seconds=seconds)

    while datetime.datetime.now() < end_time - datetime.timedelta(seconds=1):
        time.sleep(1)

    while datetime.datetime.now() < end_time:
        pass

这篇关于使用 while 的等待函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆