0

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!

Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42

1 Answers1

0

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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • It says `args=((alarm_time - now).total_seconds(), ), NameError: name 'alarm_time' is not defined` –  Jul 16 '20 at 09:16
  • I should keep this? `alarm_time = datetime.datetime.combine(now.date(), datetime.time(int(said)))` –  Jul 16 '20 at 09:17
  • @AlexZab, of course it does - you should specify it yourself. Just copy it from your code. – ForceBru Jul 16 '20 at 09:17
  • Now it says `File "Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "Python\Python36-32\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File ".py", line 124, in thread_func time.sleep(seconds) AttributeError: 'list' object has no attribute 'sleep'` –  Jul 16 '20 at 11:23
  • @AlexZab, apparently, `time` is somehow a list in your code. That's why one shouldn't reuse the names of standard functions/modules to name their variables. – ForceBru Jul 16 '20 at 11:26
  • Oh, I got it. Thank You much! –  Jul 16 '20 at 11:34
  • May I ask You another question? About timer –  Jul 20 '20 at 11:42
  • @AlexZab, yep, sure – ForceBru Jul 20 '20 at 11:43
  • How to open chat here? –  Jul 20 '20 at 11:44