简体   繁体   English

如何让 python 警报在后台运行而不让应用程序等待?

[英]How to make python alarm run in background without making application wait on it?

I'm using appjar to create a python app that includes the feature to set an alarm to go off at a certain time/date.我正在使用appjar创建一个 python 应用程序,其中包含将闹钟设置为在特定时间/日期响起的功能。 However, based on my simple implementation, when calling the alarm function in the code the application will just infinitely wait for the alarm to go off before allowing anything else to happen.然而,基于我的简单实现,当在代码中调用闹钟函数时,应用程序将无限期地等待闹钟响起,然后再允许任何其他事情发生。

I want to be able to navigate around the app without it having to wait on the alarm.我希望能够在应用程序中导航而无需等待闹钟。 What is the best way to go about doing this?执行此操作的最佳方法是什么?

Here is my alarm code:这是我的警报代码:

def setAlarm(year, month, day, hour, minute, second):

    now = datetime.datetime.now()
    date = datetime.date(year, month, day)
    time = datetime.time(hour, minute, second)
    alarmTime = datetime.datetime(year, month, day, hour, minute, second)

    while now < alarmTime:
        print("not yet")

    mixer.music.load('Alarm.wav')
    mixer.music.play(-1)

    sound = True

    while(sound):
        print("Alarm")

Check out Python Timers .查看Python 计时器 If this doesn't work, your solution will involve some kind of multi-threading or multiprocessing such that you can have two paths of execution running at the same time.如果这不起作用,您的解决方案将涉及某种多线程或多处理,以便您可以同时运行两条执行路径。

You should be able to set a timer for a short amount of time.您应该能够设置一个短时间的计时器。 When the timer goes off, have the code that it runs when it does check for the condition you're waiting for.当计时器关闭时,让它在检查您正在等待的条件时运行的代码。 If that condition still isn't met, have that code fire off a new timer to wait some more.如果仍然不满足该条件,则让该代码触发一个新计时器以等待更多时间。 When you create and start a timer, control returns immediately to your code, so you can go on and do other things.当您创建并启动计时器时,控制权会立即返回到您的代码,因此您可以继续做其他事情。

I have gone through the same problem then I solved it in my way.我遇到了同样的问题然后我用我的方式解决了它。

import time
from playsound import playsound
import threading
from datetime import datetime
import playsound

#taking input from user
alarmH = 3
alarmM = 10
amPm = 'am'

print("Weating for the alarm",alarmH,alarmM,amPm)
if (amPm == "pm"):
     alarmH = alarmH + 12

#Current Date Time
now = datetime.now()

#desired alarm time
later = datetime(2020,5,1,alarmH,alarmM,0)

#calculating the difference between two time
difference = (later - now)

#difference in seconds
total_sec=difference.total_seconds() 

def alarm_func():
    playsound.playsound('audio/alarm.mp3', True)

timer = threading.Timer(total_sec, alarm_func)
timer.start()

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

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