Python线程多次调用该方法
如果标题状态不是200,我必须卷曲一个网站并显示一条消息。逻辑工作得很好,但我在调用该方法一次时遇到了麻烦 threading.Time应该每20秒调用一次方法,但显然,它调用了多次。有人能告诉我如何让它每20秒调用一次方法吗Python线程多次调用该方法,python,python-3.x,python-multithreading,Python,Python 3.x,Python Multithreading,如果标题状态不是200,我必须卷曲一个网站并显示一条消息。逻辑工作得很好,但我在调用该方法一次时遇到了麻烦 threading.Time应该每20秒调用一次方法,但显然,它调用了多次。有人能告诉我如何让它每20秒调用一次方法吗 每20秒,您将创建一个线程,该线程将进入一个检查HTTP状态的无限循环。即使你没有使用线程。时间,你仍然会得到多个打印。删除while循环,它将按预期工作 更新 我的错误,查看文档: Time将在时间过后执行该功能。然后它就会退出。您需要做的是,在while循环中使用时间
每20秒,您将创建一个线程,该线程将进入一个检查HTTP状态的无限循环。即使你没有使用线程。时间,你仍然会得到多个打印。删除while循环,它将按预期工作 更新 我的错误,查看文档:
Time
将在时间过后执行该功能。然后它就会退出。您需要做的是,在while循环中使用时间。在while循环中休眠,并在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()
删除而为True:
,因为这是一个循环,并且多次发出请求-您从未中断过循环。@Chris如果我删除它,代码只运行一次。我必须每20秒无限次地运行它?@Chris是的,每20秒一次。@Rishav的答案就是我要做的。线程应该每20秒调用该方法。如果我删除While循环,它只运行一次,使用time.sleep
,或者@Rishav建议的方法。
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()