I'm struggling to have python periodically run some threaded function and close threads (or reuse the same threads without spawning new ones). When running the code below it spawns new threads every time the function is ran and eventually the program crashes/stops all together.
Is it possible to close threads when the task is done?
import threading
from Queue import Queue
import time
import socket
number_of_threads = 10
def check_server(address):
s = socket.socket()
s.settimeout(1)
try:
s.connect((address, 443))
return True
except:
return False
def get_online_servers(subnet):
def threader():
while True:
global online_servers
ip = q.get()
a = check_server(ip)
if a:
online_servers.append(ip)
q.task_done()
q = Queue()
for x in range(number_of_threads):
t = threading.Thread(target=threader)
t.daemon = False
t.start()
for i in range(1, 20):
ip = "{}.{}".format(subnet, i)
q.put(ip)
q.join()
return online_servers
if __name__ == '__main__':
while True:
online_servers = []
result = get_online_servers("10.0.0")
print result
time.sleep(5)