每隔一定时间重复一次sound/action

Repeat a sound/action every certain time

我正在尝试编写一个 Python 程序,每隔特定时间重现一次声音,但它并没有真正起作用。当我测试代码时,指定的时间到了,它会一直重复这个声音。

代码如下:

import os
from datetime import datetime

now = datetime.now()
currentHour = now.hour
currentMin = now.minute

#I also tested with if but it didn't work
while currentHour==15 and currentMin==33:
    os.system("aplay /home/pi/sound.wav") #Plays the sound thru aplay

这是对@bshuster13 的回答的补充。

你需要的其实是一个timer。使用繁忙的循环并检测是否是做某事的正确时间并不是一个好主意。看看 python 中的 Timer。我想你会想出更好的解决办法。

你的逻辑是错误的。

首先,while 循环很可能会在第一次迭代时结束,而您希望程序继续运行直到您告诉它为止。

除此之外,您不更新循环内的 now 变量,这基本上是个坏主意。

例如,这段代码会继续运行,当15:33时,一个声音只会播放一次。

myHour = 15
myMin = 33
is_played = False
while True:
    now = datetime.now()
    currentHour = now.hour
    currentMin = now.minute
    if currentHour == myHour and currentMin == myMin and not is_played:
        is_played = True
        os.system("aplay /home/pi/sound.wav")
    if currentHour != myHour or currentMin != myMin:
        is_played = False

Xiaotian Pei 提出了一个好主意,要有效地使用您的 CPU 资源,让我们使用 Timer 模块:

def to_play_sound(hour, min):
    now = datetime.now()
    currentHour = now.hour
    currentMin = now.minute
    if currentHour == hour and currentMin == min and not is_played:
        is_played = True
        os.system("aplay /home/pi/sound.wav")
    if currentHour != myHour or currentMin != myMin:
        is_played = False
while True:
    t = Timer(30.0, to_play_sound, [15, 33])
    t.start()

J.F. Sebastian 也提出了一个好主意:

import datetime
import subprocess
while True:
    now = datetime.now()
    # compute `deadline`
    while True:
        deadline = now.replace(hour=hour, minute=min)
        if deadline > now:
            break
        else:
            deadline += datetime.timedelta(1)
    sleep_until(deadline) # sleep
    subprocess.check_call(['aplay', '/home/pi/sound.wav']) # play the sound!

了解 sleep_until 的实施方式 here