Reputation: 1700
I have to curl a website and display a message if the header status is not 200. The logic works fine, but I'm facing trouble with calling the method once.
The threading.Time is supposed to call the method ONCE every 20 seconds but apparently, it calls it multiple times. Could someone please tell me how can I make it call the method once every 20 seconds?
import requests
import threading
def check_status(url):
while True:
status = requests.get(url)
if status.status_code != 200:
print('faulty')
def main():
threading.Timer(2.0, check_status, args=('https://www.google.com',)).start()
if __name__ == "__main__":
main()
Upvotes: 1
Views: 1917
Reputation: 5526
Every 20 seconds, you are creating a thread that enters an infinite loop which checks the HTTP status. Even if you did not use threading.Time, you would still get multiple prints. Remove the while loop and it will work as you expect.
Update
My mistake, looking at the documentation: https://docs.python.org/2/library/threading.html#timer-objects
Time
will execute the function after the time has passed. Then it will exit. What you need to do, is have time.sleep
inside the while loop, and call the function just once inside your main.
Upvotes: 0
Reputation: 3898
Just create a new timer after you finish the old one.
import requests
import threading
def check_status(url):
status = requests.get(url)
if status.status_code != 200:
print('faulty')
threading.Timer(2.0, check_status, args=('https://www.google.com',)).start()
def main():
threading.Timer(2.0, check_status, args=('https://www.google.com',)).start()
if __name__ == "__main__":
main()
Upvotes: 2