Home > Enterprise >  How can I write a loop to make the timer run every two seconds
How can I write a loop to make the timer run every two seconds

Time:11-24

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)

CodePudding user response:

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 won't recommend you to use a plain infinite loop, without any 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.

CodePudding user response:

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.

CodePudding user response:

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)
  • Related