skip to Main Content

I am currently using a counter to flag when 5 exceptions have been raised. Once the threshold is met the script notifies me by sending a Telegram message.

This works ok but I want to introduce a timeframe criteria so that a message is only send if 5 exceptions have been raised in the last 60 minutes.

I am a beginner and struggling to work out how to do it so any help would be appreciated.

count = 0

while True:
    try:
        do_stuff()

    except:
        count += 1
        if count >= 5:
            send_message_via_Telegram()
            break

3

Answers


  1. You just have to record the time difference between time at which the first exception was raised and time at which every subsequent exception is raised, then convert it to minutes and check if it’s more than 60.

    import time
    
    count = 0
    first_exception_time = None
    
    while True:
        try:
            do_stuff()
    
        except:
            if count == 0:
                first_exception_time = time.time()
            diff = time.time() - first_exception_time
            count += 1
            if count >= 5 and (diff/60) > 60:
                send_message_via_Telegram()
                break
    
    Login or Signup to reply.
  2. You can try:

    T_Sec=60*60
    count = 0
    Sec_done=0
    while True:
        Sec+=1
        try:
            do_stuff()
        except:
            count += 1
            if count >= 5 and Sec_done<=T_Sex:
                send_message_via_Telegram()
                break
        time.sleep(1)
    

    What I have done is just added 1 to Sec_done every second, and if Sec_done is less than or equal to T_Sec, it gets into the if statement.

    I have used time.sleep(1) to cause delay of a second in the loop, which would also cause a delay to run do_stuff function, you can create a new function to added sec+=1 and use threading to simultaneously run 2 or more function.

    Login or Signup to reply.
  3. I suggest that you simply keep a list of time stamps of the last 5 exceptions. In that case you don’t even need the variable count, unless you specifically want to know how many exceptions have occured in total. Instead, make sure that the list only ever contains the latest 5 exceptions and then compare the first and last elements and check if the difference is less than one hour.

    import time
    exceptions = []
    while True:
        try:
            do_stuff()
        except:
            exceptions.append(time.time())
            if len(exceptions)>5:
                exceptions.pop()
            time_between_endpoints = exceptions[-1] - exceptions[0]
            if (time_between_endpoints < 3600 and len(exceptions)==5):
                send_message_via_Telegram()
                break
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search