How to stop a loop at a certain time?

Asked

Viewed 584 times

2

I’m a beginner in Python and I’m trying to create an alarm clock... But it doesn’t "wake up" at the right time, someone can 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

  • 1

    it is better to convert to a datetime object

2 answers

3


Your logic is correct, you are only making a big mess by manipulating the date/time object by converting it to string in order to make the time comparison!

This conversion is not necessary, the comparison of a date/time object can be made through the comparison operators: >, <, ==, !=, <= and >=, normally in the same way as you would with whole numbers.

The thing may be simpler than you think, look at this:

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)

Exit:

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

2

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.