pythondatetimetimealarmassistant

How to make Python not to wait for the end of the command?


I am making a voice assistant and when I say "set alarm" program freezing and waiting for time that alarm set. So I can't talk to the assistant until alarm plays.
Here is the code

if 'alarm' in said:
    engine.say('Set')
    engine.runAndWait()
    now = datetime.datetime.now()
    alarm_time = datetime.datetime.combine(now.date(), datetime.time(int(said)))
    time.sleep((alarm_time - now).total_seconds())
    os.system("start alarm.mp3")

How to ignore it or make something to the program so it won't freeze? Maybe there are other ways for setting alarm?
Help will be appreciated!


Solution

  • You could create a thread that'll sleep for the specified amount of time. Sleeping threads don't block the main thread, so it'll continue executing.

    import threading, time, os
    
    def thread_func(seconds):
        time.sleep(seconds)
        os.system("start alarm.mp3")
    
    threading.Thread(
        target=thread_func,
        args=((alarm_time - now).total_seconds(), ),
        daemon=True
    ).start()
    # Do something else here
    

    os.system will block the execution, but it should be fairly quick.