Multi-threading with a simple timer?

Akkana Peck akkana at shallowsky.com
Tue Jul 3 14:29:03 EDT 2018


David D wrote:
> Is there a SIMPLE method that I can have a TIMER count down at a user input
> prompt - if the user doesn't enter information within a 15 second period, it
> times out.

Does this do what you want?

from threading import Timer
import sys
import os

def run_later():
    print("Timed out!")

    # sys.exit doesn't kill the main thread, but os._exit does.
    os._exit(1)

if __name__ == '__main__':
    t = Timer(15, run_later)
    t.start()
    ans = input("Enter something, or time out in 15 seconds: ")
    print("You entered", ans)
    t.cancel()
    sys.exit(0)

The only problem with that is if you want to continue with execution
after the timeout (you didn't say what you want to do in that case).
I couldn't find any straightforward way to interrupt the main thread
in a way that interrupts the input(). There's something called
_thread.interrupt_main() but it doesn't seem to work with
threading.Timer threads; maybe it would work if you created the
timer thread using _thread. Or signals, of course, as already discussed.

        ...Akkana


More information about the Python-list mailing list