You could do something like:
import requests, time, datetime # Determine "end" time -- in this case, 5 minutes from now t_end = datetime.datetime.now() + datetime.timedelta(minutes=5) while True: try: r = requests.head("http://www.testing.co.uk") if r.status_code != 200: # Do something print "Response not == to 200." else: # Do something else print "Response is 200 - OK" break # Per comments time.sleep(30) # Wait 30 seconds between requests except requests.ConnectionError as e: print "NOT FOUND - ERROR" # If the time is past the end time, re-raise the exception if datetime.datetime.now() > t_end: raise e time.sleep(30) # Wait 30 seconds between requests
The important line is:
if datetime.datetime.now() > t_end: raise e
If the condition isn't met (less that 5 minutes have elapsed), the exception is silently ignored and the while loop continues.
If the condition is met, the exception is re-raised to be handled by some other, outer code or not handled at all -- in which case you'll see the exception "break" (in your words) the program.
The benefit of using this approach over something like (instead of while True:):
while datetime.datetime.now() > t_end:
is that if you find yourself outside of the while loop, you know you got there from break and not from 5 minutes elapsing. You also preserve the exception in case you want to do something special in that case.