轮询将来的特定时间

时间:2016-02-21 22:53:42

标签: python python-2.7 raspberry-pi

所以我一直在编写一个关于覆盆子pi的python 2.7中的一个谈论AI的东西,我遇到了一个错误!

我正在设置一个闹钟功能,所以你设置你想要它唤醒你的时间然后它在那个时候播放一首歌然后在读出一个设置的消息之后。我已经得到了相当远的代码,它之前的工作完全正常,但突然它停止工作,我无法弄清楚为什么。感觉它正在跳过while循环,但我真的不确定!

继承代码,忽略只是为了让它说话的'speak'命令。

if userInput == "set alarm":
            alarmnow = datetime.datetime.now()
            espeak.synth("What hour would you like to set the alarm?")
            hour = raw_input("What hour would you like to set the alarm?: ")
            espeak.synth("What minute would you like to set the alarm?")
            minute = raw_input("What minute would tou like to set the alarm?: ")
            espeak.synth("What would you like me to say after the alarm?")
            message = raw_input("What would you like me to say after the alarm?: ")
            while alarmnow.hour != int(hour) and alarmnow.minute != int(minute):
                    time.sleep(1)
            os.system("omxplayer takemetochurch.mp3")
            espeak.synth(message)
            print(message)

请帮帮我,这真让我烦恼,我已经做了很长时间了,我不能为我的生活搞清楚了!

2 个答案:

答案 0 :(得分:2)

你的问题是你永远不会更新现在'所以你的时钟将永远轮询。你可以重做你的while循环来获得每个循环的时间。

但你应该尽可能避免轮询。效率低下,如果系统中出现其他问题,您可能会错过窗口。在你的情况下这是不太可能的,因为你只需要在一分钟之内完成......除非夏令时达到并完全错过。

由于您已经有几小时和几分钟而且很容易转换为秒,所以只需要全时睡觉

if userInput == "set alarm":
            espeak.synth("What hour would you like to set the alarm?")
            hour = raw_input("What hour would you like to set the alarm?: ")
            espeak.synth("What minute would you like to set the alarm?")
            minute = raw_input("What minute would tou like to set the alarm?: ")
            espeak.synth("What would you like me to say after the alarm?")
            message = raw_input("What would you like me to say after the alarm?: ")
            # setup alarm for today but if its already past, go to tomorrow
            now = datetime.datetime.now()
            nominate = datetime.datetime(now.year, now.month, now.day,
                int(hour), int(minute))
            if nominate < now:
                nominate += datetime.timedelta(days=1)
            time.sleep((nominate - now).seconds)
            os.system("omxplayer takemetochurch.mp3")
            espeak.synth(message)
            print(message)

答案 1 :(得分:0)

message = raw_input("What would you like me to say after the alarm?: ")
alarmnow = datetime.datetime.now()
while alarmnow.hour != int(hour) and alarmnow.minute != int(minute):
    time.sleep(1)
    alarmnow = datetime.datetime.now()