Multi-threading with a simple timer?
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
# sys.exit doesn't kill the main thread, but os._exit does.
if __name__ == '__main__':
t = Timer(15, run_later)
ans = input("Enter something, or time out in 15 seconds: ")
print("You entered", ans)
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.
More information about the Python-list