Just as I replied in
How to perform a task at a precise time in time?
You don’t need to create a repeat loop and keep checking the time every second, you just set the call schedule 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 to, 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 on Repl.it | Github GIST
it is better to convert to a datetime object
– tomasantunes