Home » Ruby programming

How to tell Ruby program to wait for some amount of time?

Example of sleep() method: Here, we are going to learn how to tell Ruby program to wait for some amount of time?
Submitted by Hrithik Chandra Prasad, on September 10, 2019

Example of sleep() method

Sometimes, you may need to halt the execution for some time. This may occur when you are working on a geocoding piece or a sidekiq job in a Ruby application. To avoid the Google API query limit, you may need to sleep the program for 1 second. In such case, you will require Ruby sleep() method which is predefined in Ruby's library. You may require to sleep your program for an arbitrary amount of time in many situations.

Ruby sleep() method

sleep() method accepts number of seconds as argument and suspends the thread of execution for the amount of seconds being passed as parameter. The parameter can be passed as number or float or fraction. If you are working with Ruby on Rails, then you get the facility to pass parameter with .seconds, .minutes or .hours and it can be suspended up to .days as well.

If you do not pass any argument with sleep or do not specify, for how much time you want the execution to be suspended then your program will sleep forever.

Let us understand the concept with the help of short program codes.

Example 1:

=begin
Code to make execution sleep for 1 second.
=end

puts "Hello world! Greetings from Includehelp.com"
sleep 1
puts "bye"

Output

Hello world! Greetings from Includehelp.com
bye
[Finished in 1.3s]

The above code is written and tested in Sublime Text. There you can check the execution time. The above program is taking .3 seconds in execution and 1 second is the sleep time which is suspending the thread.

Now, let us verify the execution time bypassing another argument in the sleep method.

Example 2:

=begin
Code to make execution sleep for 5 seconds.
=end  

puts "Hello world! Greetings from Includehelp.com"
sleep 5
puts "bye"

Output:

Hello world! Greetings from Includehelp.com
bye
[Finished in 5.3s]

The above code is also written and tested in Sublime Text. The execution time taken by the program is ".3" seconds and the sleep time is 5 seconds because we have passed 5 seconds in the sleep() method as an argument.

Now let us verify whether sleep method accepts float argument or not with the help of example given below,

Example 3:

=begin
Code to make execution sleep for 0.75 second.
=end	

puts "Hello world! Greetings from Includehelp.com"
sleep 0.75
puts "bye" 

Output

Hello world! Greetings from Includehelp.com
bye
[Finished in 1.1s]

With the help of above code, you can understand that sleep variable accepts float argument as well.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.