How to stop a loop at a certain time?

2

I'm a beginner in Python and I'm trying to create an alarm clock ... But it does not "Wake up" on time, can anyone help me?

import datetime
import time

print("Digite a hora para ligar (HH:MM)")
t_desp = str(input(""))
t_desp += ":00"
print("Despertar as: ", t_desp)
while True:
    t_agora = str(datetime.datetime.now().time())
    t_agora = t_agora.split(".")
    print(t_agora[0])
    if t_agora == t_desp:
       print("Acordar")
       break
    time.sleep(1)

Thank you

    
asked by anonymous 15.06.2018 / 05:56

2 answers

3

Your logic is correct, you're only making a big mess by manipulating the date / time object when converting it to string in order to compare timetables!

This conversion is not necessary, the comparison of a date / time object can be done through comparison operators: > , < , == , != , <= and >= , usually the same as you would for integers.

The thing may be simpler than you think, see:

import datetime
import time

entrada = str(input("Digite a hora para ligar (HH:MM)"))

hr = entrada.split(':')

t_desp = datetime.datetime.combine( datetime.datetime.now().date(),
                                    datetime.time( int(hr[0]), int(hr[1])) )

print("Despertar as: ", t_desp )

while True:

    t_agora = datetime.datetime.now()

    print(t_agora)

    if t_agora >= t_desp:
       print("Acordar")
       break

    time.sleep(1)

Output:

Digite a hora para ligar (HH:MM): 09:04
Despertar as:  2018-06-15 09:04:00
2018-06-15 09:03:52.754612
2018-06-15 09:03:53.755732
2018-06-15 09:03:54.756937
2018-06-15 09:03:55.758121
2018-06-15 09:03:56.759319
2018-06-15 09:03:57.760200
2018-06-15 09:03:58.761378
2018-06-15 09:03:59.762585
2018-06-15 09:04:00.763779
Acordar
    
15.06.2018 / 14:13
2

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

    
15.06.2018 / 14:46