Just as I replied in
How to perform a task at a precise time in time?
You do not need to create a loop repetition and check the time every second, you simply set the schedule of the call to a function at the time you want.
import sched, time, threading, sys
# Executará no dia 2018-06-15 às 12:00:00
trigger = time.mktime((2018, 6, 15, 12, 0, 0, 0, 0, 0))
def task(trigger):
sys.stdout.write('Trim! Trim! Hora de acordar')
s = sched.scheduler(time.time, time.sleep)
s.enterabs(trigger, 1, task, argument=(trigger,))
t = threading.Thread(target=s.run)
t.start()
while t.is_alive(): pass # Simula o programa executando normalmente
For example, you can do other things in the code if you need it while the alarm is not triggered:
import sched, time, threading, sys
print('Para quando deseja configurar o alarme?')
year = int(input('Ano? '))
month = int(input('Mês? '))
day = int(input('Dia? '))
hour = int(input('Hora? '))
minute = int(input('Minutos? '))
second = int(input('Segundos? '))
trigger = time.mktime((year, month, day, hour, minute, second, 0, 0, 0))
def task(trigger):
sys.stdout.write('Trim! Trim! Hora de acordar')
s = sched.scheduler(time.time, time.sleep)
s.enterabs(trigger, 1, task, argument=(trigger,))
t = threading.Thread(target=s.run)
t.start()
print('Enquanto esperamos, que tal um jogo?')
while t.is_alive():
from random import randint
a = randint(-100, 100)
b = randint(-100, 100)
answer = int(input(f'Quanto vale {a}+({b})? '))
print('Muito bem!' if a+b == answer else 'Ahm... acho que não')
See working at Repl.it | GitHub GIST