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
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.
You can try:
What I have done is just added 1 to
Sec_done
every second, and ifSec_done
is less than or equal toT_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 rundo_stuff
function, you can create a new function to addedsec+=1
and usethreading
to simultaneously run 2 or more function.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.