'How to end threads after a specified amount of time?

I have this python script that just starts up threads to listen on some ports on the localhost.

#!/usr/bin/python3

import socket
import threading
import concurrent.futures

threads = []

def listen_on_port(port):
    HOST = ''                 # Symbolic name meaning all available interfaces
    PORT = int(port)          # Arbitrary non-privileged port
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen(1)
        conn, addr = s.accept()
        print(addr,conn)


def main(ports):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        for port in ports:
            executor.submit(listen_on_port,port)

if __name__ == '__main__':
    main(ports=[50010,50020,50030])

When I run this script it listens on the ports as expected. I use this script to test that the firewall rules are allowing connections on those ports. And on another system I execute nc -zv my-host 50010 and the thread is listening on port 50010 terminates, which is what I want.

But, I would like to make two improvements: 1) have the threads die after X seconds, 2) Run the threads in the back ground like daemons so that my script will exit and leave the threads running.

I have been trying to figure this out for days and I have gotten no where. Please help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source