Tell Ruby Program to Wait some amount of time
Like this:
sleep(num_secs)
The num_secs
value can be an integer or float.
Also, if you're writing this within a Rails app, or have included the ActiveSupport library in your project, you can construct longer intervals using the following convenience syntax:
sleep(4.minutes)
# or, even longer...
sleep(2.hours); sleep(3.days) # etc., etc.
# or shorter
sleep(0.5) # half a second
How to put a delay on a loop in Ruby?
The 'comment' above is your answer, given the very simple direct question you have asked:
1.upto(5) do |n|
puts n
sleep 1 # second
end
It may be that you want to run a method periodically, without blocking the rest of your code. In this case, you want to use a Thread (and possibly create a mutex to ensure that two pieces of code are not attempting to modify the same data structure at the same time):
require 'thread'
items = []
one_at_a_time = Mutex.new
# Show the values every 5 seconds
Thread.new do
loop do
one_at_a_time.synchronize do
puts "Items are now: #{items.inspect}"
sleep 5
end
end
end
1000.times do
one_at_a_time.synchronize do
new_items = fetch_items_from_web
a.concat( new_items )
end
end
Making a time counter while waiting for user input in ruby
I guess I found a solution!
dog = Dog.new 'Yoshi'
def play pet
while pet.is_alive
user_action = nil
timer_thread = Thread.new do
while user_action == nil
(1..10).each do |number|
sleep(1)
number
if number == 10
pet.time_goes_on
end
break if (user_action != nil)
end
end
end
user_action = gets.chomp
case user_action
when "play"
pet.play_fetch
when "eat"
pet.feed
when "train"
pet.training
when "sleep"
pet.sleep
when "walk"
pet.take_for_a_walk
else
puts "invalid command, try again"
play(pet)
end
timer_thread.join
end
end
play(dog)
Ruby sleep or delay less than a second?
sleep(1.0/24.0)
As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.
You could try one of these solutions:
- Use a timer which fires 24 times a second with the drawing code.
- Create as many frames as possible, create the motion based on the time passed, not per frame.
Why does my Ruby program takes different times to execute?
Why does this code return a different execution time every time I run it?
Because your computer doesn't perform the exact same physical task every time it runs.
Maybe the data happened to be stored in slightly more/less efficient location on the RAM? Maybe your computer was too hot/cold, so performed differently. Maybe you also have 20 StackOverflow tabs open, which was using up system resources :D
Plus, in order to get a more accurate benchmark of how quickly some code runs, you need to decrease the error margin by performing the same operation lots of times.
I would recommend trying the benchmark-ips
library if you wish to get some more reliable measurements of your code's performance.
Wait until value appears in the hash
I think you need timeout
and a way to force stop polling process, moreover, you maybe need an abstract to improve in future.
class Poller
def self.poll(key:, from_source:, options: {})
start_time = Time.now
catch(:stop_polling) do
loop do
message = from_source.get_message(key)
if message.nil?
wait_time = Time.now - start_time
throw :stop_polling if wait_time > options[:timeout]
else
yield(message) if block_given?
throw :stop_polling
end
end
end
end
end
def monitor_payment_hash(key)
Poller.poll key: key, from_source: @uuid.payment_create, options: {timeout: 60} do |message|
# write to the global message holders
# or handle message by block
yield(message) if block_given?
end
end
You maybe need to add more logic such as retry if timeout, polling a list of keys, log... I recommend you learn how to build a long polling from this source : https://github.com/aws/aws-sdk-ruby/blob/version-3/gems/aws-sdk-sqs/lib/aws-sdk-sqs/queue_poller.rb
It's possible wait for a variable in Ruby, (without sleep)?
What about promises? Could it be what you are looking for?
https://ruby-concurrency.github.io/concurrent-ruby/1.1.5/Concurrent/Promise.html
From the docs:
Promises are similar to futures and share many of the same behaviours.
Promises are far more robust, however. Promises can be chained in a
tree structure where each promise may have zero or more children.
Promises are chained using the then method. The result of a call to
then is always another promise. Promises are resolved asynchronously
(with respect to the main thread) but in a strict order: parents are
guaranteed to be resolved before their children, children before their
younger siblings. The then method takes two parameters: an optional
block to be executed upon parent resolution and an optional callable
to be executed upon parent failure. The result of each promise is
passed to each of its children upon resolution. When a promise is
rejected all its children will be summarily rejected and will receive
the reason.
Also you can see this guide:
https://medium.com/@gauravbasti2006/lets-keep-our-promise-in-ruby-e45925182fdc
Related Topics
Calling Another Method in Super Class in Ruby
How to Install Ruby 1.9.3 in MAC Os X Mountain Lion Without Xcode
How to Find the Key of the Largest Value Hash
Foreman Only Shows Line with "Started with Pid #" and Nothing Else
Rails 4 Turbolinks with Google Analytics
Running Pod Setup Gives Me "Bad Interpreter: No Such File or Directory" Error
Determine Ruby Version from Within Rails
Capistrano Ssh::Authenticationfailed, Not Prompting for Password
Difference Between @Instance_Variable and Attr_Accessor
Best Practice for Rails App to Run a Long Task in the Background
Paperclip Renaming Files After They'Re Saved
Difference Between Each.With_Index and Each_With_Index in Ruby
Rails 4 Unpermitted Parameters for Array
How to Pass an Argument to Array.Map Short Cut
Libxml2 Missing MAC Os X 10.10
Monkey Patching Devise (Or Any Rails Gem)
Generate a Powerset of a Set Without Keeping a Stack in Erlang or Ruby