Making a timer in Ruby

2019-05-26 10:20发布

问题:

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)?

回答1:

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:

  1. The user_input thread, which gets a string from the user and sets its value thread variable
  2. The timer thread, which sleeps for three seconds and then kills the user_input thread
  3. The main thread, which spawns the other two and then waits for the user_input thread to finish

Without 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.



回答2:

Somethink like this?

puts "In how many Seconds you want me to beep?"
t = gets.to_i

sleep t
puts "\a WAKE UP!"


回答3:

My way :

comt = 0
while (comt < 10)
    sleep(1)
    comt = comt +1
    puts comt
end#while

That display : 1 2 3 ... 10



标签: ruby timer