定期检查网络服务器是否有线程
Regularly check whether a webserver is up with a Thread
我写了一个线程 class 来测试网络服务器是否启动。
import urllib
import threading
import time
import Queue
class Thread_CheckDeviceState(threading.Thread):
def __init__(self, device_ip, queue, inter=0.1):
self._run = True
self._codes = {}
self._queue = queue
self._device_ip = device_ip
self._inter = inter
self._elapsed = 0
threading.Thread.__init__(self)
def stop(self):
self._run = False
def run(self):
start = time.time()
while self._run:
try:
code = urllib.urlopen(self._device_ip).getcode()
except Exception:
code = "nope"
finally:
measure = time.time()
self._elapsed += measure-start
print self._elapsed, code
self._codes.update(
{self._elapsed:code}
)
time.sleep(self._inter)
self._queue.put(self._codes)
q = Queue.Queue()
thread = Thread_CheckDeviceState("http://192.168.1.3", q)
thread.start()
time.sleep(10)
thread.stop()
print q.get()
它工作正常 - 直到我断开我的电脑与网络的连接。从那一刻起,线程在停止之前什么都不做。我希望它继续并将 code
设置为 "nope"
,就像我在异常处理程序中写的那样。为什么不起作用
您需要使用urllib2
,并在调用urlopen()时指定一个timeout
参数。
我写了一个线程 class 来测试网络服务器是否启动。
import urllib
import threading
import time
import Queue
class Thread_CheckDeviceState(threading.Thread):
def __init__(self, device_ip, queue, inter=0.1):
self._run = True
self._codes = {}
self._queue = queue
self._device_ip = device_ip
self._inter = inter
self._elapsed = 0
threading.Thread.__init__(self)
def stop(self):
self._run = False
def run(self):
start = time.time()
while self._run:
try:
code = urllib.urlopen(self._device_ip).getcode()
except Exception:
code = "nope"
finally:
measure = time.time()
self._elapsed += measure-start
print self._elapsed, code
self._codes.update(
{self._elapsed:code}
)
time.sleep(self._inter)
self._queue.put(self._codes)
q = Queue.Queue()
thread = Thread_CheckDeviceState("http://192.168.1.3", q)
thread.start()
time.sleep(10)
thread.stop()
print q.get()
它工作正常 - 直到我断开我的电脑与网络的连接。从那一刻起,线程在停止之前什么都不做。我希望它继续并将 code
设置为 "nope"
,就像我在异常处理程序中写的那样。为什么不起作用
您需要使用urllib2
,并在调用urlopen()时指定一个timeout
参数。