简体   繁体   中英

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. The problem is that the first time the sound works after 2 seconds, the next times it is executed immediately. 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. 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. 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. Therefore you should work with timedeltas or take a look at 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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