简体   繁体   English

如何编写循环以使计时器每两秒运行一次

[英]How can I write a loop to make the timer run every two seconds

I have a question on how I am able to set the timer so that every time it exits the loop it sets the time back to 2 seconds.我有一个关于如何设置计时器的问题,以便每次退出循环时都会将时间设置回 2 秒。 The problem is that the first time the sound works after 2 seconds, the next times it is executed immediately.问题是声音第一次在 2 秒后起作用,下一次立即执行。 Thank you very much in advance for any advice.非常感谢您的任何建议。

This is my code:这是我的代码:


            time = 2
            while time > 0:
                timer = datetime.timedelta(seconds=time)
                time -= 1
                duration = 1000
                freq = 440
            winsound.Beep(freq, duration)

I am not sure if you meant that, but for me it seems like you just want to wait 2 seconds before executing the next steps.我不确定您是不是这个意思,但对我来说,您似乎只想等待 2 秒钟,然后再执行下一步。 You can do that like so:你可以这样做:

import time

while True:
    time.sleep(2) # waits 2 seconds
    winsound.Beep(440, 1000)

Anyways I don't recommend you to use a plain infinite loop, without a break statement.无论如何,我不建议您使用没有 break 语句的普通无限循环。 Therefore I recommend you to add one, like down below.因此,我建议您添加一个,如下所示。

import time

while True:
    time.sleep(2) # waits 2 seconds
    winsound.Beep(440, 1000)

    if True: # break on a specific statment
        break

Edit: As CrazyChucky mentioned in the comments, this approach should work fine in most of the cases, but it can end up being more than two seconds sometimes.编辑:正如 CrazyChucky 在评论中提到的,这种方法在大多数情况下应该可以正常工作,但有时可能会超过两秒。 Therefore you should work with timedeltas or take a look at scheduler .因此,您应该使用 timedeltas 或查看scheduler

To be more accurate as possible use:为了尽可能准确,请使用:

import time

timer = 0
step = 2
t0 = time.time()
while True:
    timer = time.time() - t0
    wait = step - timer
    time.sleep(wait)
    print(time.time())
    winsound.Beep(freq, duration)
    t0 = time.time()

This script take in count the execution time of script lines for your computer.此脚本计算您计算机的脚本行的执行时间。

You just have to reinitialize the time at the end of the loop您只需要在循环结束时重新初始化时间

time = 2
while True:
    timer = datetime.timedelta(seconds=time)
    time -= 1
    duration = 1000
    freq = 440
    if time == 0: 
        time = 2
        break
winsound.Beep(freq, duration)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM