简体   繁体   English

如何在 python 中每 n 秒重复 x 次?

[英]how to make something repeat x amount of times every n seconds in python?

Let's say, i want a beeping sound be heard a total of 5 times, with 5 second break with each beep.比方说,我希望总共听到 5 次哔哔声,每次哔哔声中断 5 秒。 For that, i tried using threading module, and made this:为此,我尝试使用线程模块,并做了这个:

import threading
import winsound
i = 0
def beep():
   global i
   while i < 5:
         i += 1
         threading.Timer(5.0, beep).start()
         winsound.PlaySound("beep", winsound.SND_FILENAME)

beep()

This code repeats it succesfully i amount of times, but ignores a time interval and instead does it on a much faster, equally distributed unchangeable interval.这段代码成功地重复了 i 次,但忽略了一个时间间隔,而是在一个更快、均匀分布的不可更改的间隔上执行它。 I know that happens because of how while loop works, but I cant seem to find any alternative.我知道这是因为 while 循环是如何工作的,但我似乎找不到任何替代方案。 Every piece of information would come in handy!每一条信息都会派上用场!

use time module使用时间模块

import time进口时间

time.sleep(int x in seconds) time.sleep(int x in seconds)

I got this to work ok:我让这个工作正常:

import threading
import winsound

def beep(n):
    if n == 0:
        return
    for i in range(5):
        winsound.Beep(4000,100)
    threading.Timer(5.0, beep, args=(n-1,)).start()

beep(4)

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

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