Search code examples
pythonpython-3.xdatetimetimealarm

Problems with python alarm at specified hours


I'm trying to make a "alarm" for my classes and it does that when a certain hour comes it does something (in this case it just prints, and i will change that when the code works) and it repeats until next alarm.The problem here is that when i run the code 1 min before it prints it's time , and then it reaches the alarm time and it still prints the same and not not yet.

I want the code to keep running after the if statements. Here's the code:

from datetime import datetime
import time
now = datetime.now()

current_time = now.strftime("%H:%M")
today = now.strftime("%A")

cn = "22:14"
ing ="21:23"

day = {0:"Monday", 1:"Tuesday", 2:"Wednesday"
, 3:"Thursday", 4:"Friday", 5:"Saturday", 6:"Sunday"}


def mday():
 if (today == day[0]) and (current_time == cn):
  print("its time")
  time.sleep(1)
  mday()
 else:
  print("not yet")
  time.sleep(1)
  mday()
mday()

Solution

  • The main problem with your code (why it does not work at all), is that you do not update the values of the today and current_time variables. That you sleep for one second in each call to mday() does not affect these variables. You need to update them right at the entry to mday.

    The second problem is that you have infinite recursion here. Infinite loops run forever, which is what you want, I guess. Infinite recursion, on the other hand, simply uses up the stack, and crashes you application. You would need to convert the recursive function mday to one with an infinite loop. To do that, place all the if statement from inside mday inside a forever loop: (while True:), and also remove the two recursive calls from the end of the branches. You can also take the sleep calls out of the if - remove one of them, and place the other after the the content of the else block:

    from datetime import datetime
    import time
    
    cn = "22:14"
    ing ="21:23"
    
    day = {
      0:"Monday",
      1:"Tuesday",
      2:"Wednesday",
      3:"Thursday",
      4:"Friday",
      5:"Saturday",
      6:"Sunday"
    }
    
    def mday():
      while True:
        # Update current time values
        now = datetime.now()
        current_time = now.strftime("%H:%M")
        today = now.strftime("%A")
        # Print alarm/no-alarm message
        if (today == day[0]) and (current_time == cn):
          print("its time")
        else:
          print("not yet")
        time.sleep(1)
    
    mday()
    

    There are many ways this code can be optimized, but the above will produce roughly the result you want.