I want to make a timer in Ruby, where after a certain amount of time that the user chooses, the timer rings, or a message pops up. Also, would it be possible to make the timer ring until the user does a certain thing (such as a math problem)?
Use threads:
user_input = Thread.new do
print "Enter something: "
Thread.current[:value] = gets.chomp
end
timer = Thread.new { sleep 3; user_input.kill; puts }
user_input.join
if user_input[:value]
puts "User entered #{user_input[:value]}"
else
puts "Timer expired"
end
Three threads are running in this code:
user_input thread, which gets a string from the user and sets its value thread variabletimer thread, which sleeps for three seconds and then kills the user_input threaduser_input thread to finishWithout the timer thread, the code would appear to work exactly like a single-threaded one that prompts for user input and then continues. The execution of the two threads is serialized using #join. The main thread gets the result of the user interaction by looking at the user_input's value thread variable.
The addition of the timer thread causes the user_input thread to terminate early (3 seconds in this case). When this happens, the user_input thread has not set its value thread variable, and so returns nil when the main thread interrogates it for this variable. This is how the main thread determines whether user_input terminated due to accepting input from the user, or being killed by the timer thread.
Somethink like this?
puts "In how many Seconds you want me to beep?"
t = gets.to_i
sleep t
puts "\a WAKE UP!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With