我必须卷曲一个网站,并显示一条消息,如果标题状态不是200。逻辑运行得很好,但我在调用该方法时遇到了麻烦。
threading.Time应该每隔20秒调用一次方法,但很明显,它调用了多次。谁能告诉我怎么才能让它每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()
发布于 2018-06-03 07:14:02
只需在完成旧的计时器后创建一个新的计时器。
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()
发布于 2018-06-03 07:09:15
每隔20秒,您就会创建一个进入无限循环的线程,该线程将检查HTTP状态。即使你没有使用threading.Time,你仍然会得到多个指纹。删除while循环,它将按您预期的那样工作。
更新
我的错误,查看文档:https://docs.python.org/2/library/threading.html#timer-objects
Time
将在该时间过后执行该函数。然后它将退出。您需要做的是,在while循环中使用time.sleep
,并且只在main中调用该函数一次。
https://stackoverflow.com/questions/50661888
复制相似问题