Python线程多次调用该方法
Python threading calls the method multiple times
如果 header 状态不是 200,我必须卷曲一个网站并显示一条消息。逻辑工作正常,但我在调用该方法一次时遇到了麻烦。
threading.Time 应该每 20 秒调用一次方法 ONCE 但显然,它调用了多次。谁能告诉我如何让它每 20 秒调用一次 方法?
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()
每 20 秒,您将创建一个线程,该线程进入一个检查 HTTP 状态的无限循环。即使您不使用 threading.Time,您仍然会得到多个打印件。删除 while 循环,它将如您所愿地工作。
更新
我的错误,查看文档:https://docs.python.org/2/library/threading.html#timer-objects
Time
将在时间过后执行函数。然后它会退出。您需要做的是在 while 循环中使用 time.sleep
,并在您的 main.
中调用该函数一次。
完成旧计时器后,只需创建一个新计时器即可。
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()
如果 header 状态不是 200,我必须卷曲一个网站并显示一条消息。逻辑工作正常,但我在调用该方法一次时遇到了麻烦。
threading.Time 应该每 20 秒调用一次方法 ONCE 但显然,它调用了多次。谁能告诉我如何让它每 20 秒调用一次 方法?
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()
每 20 秒,您将创建一个线程,该线程进入一个检查 HTTP 状态的无限循环。即使您不使用 threading.Time,您仍然会得到多个打印件。删除 while 循环,它将如您所愿地工作。
更新
我的错误,查看文档:https://docs.python.org/2/library/threading.html#timer-objects
Time
将在时间过后执行函数。然后它会退出。您需要做的是在 while 循环中使用 time.sleep
,并在您的 main.
完成旧计时器后,只需创建一个新计时器即可。
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()