Python: Setting multiple continuous timeouts
<p>I want to have some kind of server that receives events (i.e using sockets), and each event has a different ID (i.e dst port number). </p>

<p>Is there a way that from the moment I see the first packet of an specific ID, I start some kind of timeout (i.e, 1ms), and if in that time nothing else with the same ID is received  an event is triggered, but if something is received the timeout is reset to 1ms. </p>

<p>I have seen that something like that can be done by using <code>signals</code> and the <code>SIGALARM</code> signal. However, I want to keep multiple "timers" for every  different ID.</p>

<p>Sounds like a job for <code>select</code>. As you are using sockets, you have a socket descriptor for a client (presumably one for each client but as long as you have one, it works). So you either want to wait until a packet arrives on one of your sockets or until a timeout occurs. This is exactly what <code>select</code> does.</p>

<p>So calculate the expiration time for each client when you receive a message, then in your main loop, simply calculate the soonest-to-expire timeout and provide that as the <code>timeout</code> parameter to <code>select.select</code> (with all the socket descriptors as the <code>rlist</code> parameter). Then you get awakened when a new packet/message arrives or when the oldest timeout expires. If it's a new packet, you process the packet and reset that provider's timeout to 1ms; otherwise, you do whatever you do when the timeout expires. </p>

<p>Then calculate the next-to-expire timeout. Rinse. Lather. Repeat.</p>

<p>Something like this:</p>

<pre><code>now = time.time()
timeout = min([(client.expiration - now) for client in clients_list])
rrdy, wrdy, xrdy = select.select([client.sock for client in clients_list], [], [], timeout)
if not rrdy:
    # Timeout
    now = time.time()
    for client in clients_list:
        if client.expiration &lt; now:
            process_timeout(client)
else:
    # Process incoming messages
    for rsock in rrdy:
        process_message(rsock.recv(4096))
        client.expiration = time.time() + .001
</code></pre>

python sockets timeout signals